This repository has been archived by the owner on Oct 17, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
misc.go
467 lines (422 loc) · 12.4 KB
/
misc.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
package opendcm
import (
"crypto/rand"
"fmt"
"io"
"log"
"math/big"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
)
/*
===============================================================================
Configuration
===============================================================================
*/
// OpenDCMRootUID contains the official designated root UID prefix for OpenDCM
// Issued by Medical Connections Ltd
const OpenDCMRootUID = "1.2.826.0.1.3680043.9.7484."
// OpenDCMVersion equals the current (or aimed for) version of the software.
// It is used commonly in creating ImplementationClassUID(0002,0012)
const OpenDCMVersion = "0.2"
const SCPMaxBytes = 2 * 1024 * 1024
// ExitOnFatalLog specifies whether the application should `os.Exit(1)` on a fatal log message
var ExitOnFatalLog = true
// Config represents the application configuration
type Config struct {
Version string
OpenFileLimit int
RootUID string
LogLevel string
/* By enabling `StrictMode`, the parser will reject DICOM inputs which either:
- TODO: Contain an element with a value length exceeding the maximum allowed for its VR
- Contain an element with a value length exceeding the remaining file size. For example incomplete Pixel Data.
*/
StrictMode bool
// DicomReadBufferSize is the number of bytes to be buffered from disk when parsing dicoms
DicomReadBufferSize int
// AET
AET string
AEBindIP string
AEBindPort int
// do not access / write `_set`. It is used internally.
_set bool
}
// intFromEnv retrieves `key` from the OS environment.
// if the key is not found, or cannot be expressed as an integer,
// `found` will be false.
func intFromEnv(key string) (val int, found bool) {
valStr, found := os.LookupEnv(key)
if !found {
return
}
val, err := strconv.Atoi(valStr)
if err != nil {
found = false
}
return
}
func intFromEnvDefault(key string, def int) (val int) {
val, found := intFromEnv(key)
if !found {
val = def
}
return
}
func strFromEnv(key string) (string, bool) {
return os.LookupEnv(key)
}
func strFromEnvDefault(key string, def string) (val string) {
val, found := strFromEnv(key)
if !found {
val = def
}
return
}
func boolFromEnv(key string) (val bool, found bool) {
valStr, found := os.LookupEnv(key)
if !found {
return
}
val, err := strconv.ParseBool(valStr)
if err != nil {
found = false
}
return
}
func boolFromEnvDefault(key string, def bool) (val bool) {
val, found := boolFromEnv(key)
if !found {
val = def
}
return
}
var config Config
// initialiseConfig initialises the applications configuraiton.
// Will set config from environment if not already set.
func initialiseConfig() {
if !config._set {
config.OpenFileLimit = intFromEnvDefault("OPENDCM_OPENFILELIMIT", 64)
config.StrictMode = boolFromEnvDefault("OPENDCM_STRICTMODE", false)
config.DicomReadBufferSize = intFromEnvDefault("OPENDCM_BUFFERSIZE", 2*1024*1024)
config.LogLevel = strings.ToLower(strFromEnvDefault("OPENDCM_LOGLEVEL", "info"))
config.AET = strFromEnvDefault("OPENDCM_AET", "OPENDCM")
config.AEBindIP = strFromEnvDefault("OPENDCM_AEIP", "0.0.0.0")
config.AEBindPort = intFromEnvDefault("OPENDCM_AEPORT", 6789)
switch config.LogLevel {
case "debug", "info", "warn", "error", "fatal", "none", "disabled", "0", "1", "2", "3", "4", "5":
SetLoggingLevel(config.LogLevel)
default:
panic(`Invalid "OPENDCM_LOGLEVEL". Choose from "debug", "info", "warn", "error", "fatal", or "none".`)
}
config._set = true
}
}
// hook for package initialisation.
func init() {
initialiseConfig()
}
// OverrideConfig overrides the configuration parsed from environment with the one provided
func OverrideConfig(newconfig Config) {
if !newconfig._set { // to prevent being reverted with subsequent calls to `GetConfig`
newconfig._set = true
}
config = newconfig
}
/*
===============================================================================
Logging
===============================================================================
*/
const (
ansiRed = 31
ansiGreen = 32
ansiYellow = 33
ansiMagenta = 35
)
// colourForLevel returns the ANSI colour code for `level`
func colourForLevel(level string) (ansiColour int) {
switch level {
case "D":
ansiColour = ansiMagenta
case "I":
ansiColour = ansiGreen
case "W":
ansiColour = ansiYellow
case "E", "F":
ansiColour = ansiRed
default:
ansiColour = 0
}
return
}
var (
infolog = newLogger("I", os.Stdout)
debuglog = newLogger("D", os.Stdout)
warnlog = newLogger("W", os.Stdout)
errorlog = newLogger("E", os.Stderr)
fatallog = newLogger("F", os.Stderr)
)
// awareLogger encapsulates a `log.Logger` to provide awareness of both
// whether the logger is enabled, and whether the output is a character device.
type awareLogger struct {
*log.Logger
Enabled bool
SupportsColour bool
}
// SupportsColour returns whether `f` is a character device (UNIX terminal)
func SupportsColour(f *os.File) bool {
stat, err := f.Stat()
if err != nil {
panic(err)
}
supports := (stat.Mode() & os.ModeCharDevice) != 0
if supports && runtime.GOOS == "windows" {
supports = false
}
return supports
}
// Infof calls `infolog.Output` to print to the logger.
// Arguments are handled in the manner of fmt.Printf
func Infof(format string, v ...interface{}) {
if infolog.Enabled {
infolog.Output(2, fmt.Sprintf(format, v...))
}
}
// Info calls `infolog.Output` to print to the logger.
// Arguments are handled in the manner of fmt.Print
func Info(v ...interface{}) {
if infolog.Enabled {
infolog.Output(2, fmt.Sprint(v...))
}
}
// Debugf calls `debuglog.Output` to print to the logger.
// Arguments are handled in the manner of fmt.Printf
func Debugf(format string, v ...interface{}) {
if debuglog.Enabled {
debuglog.Output(2, fmt.Sprintf(format, v...))
}
}
// Debug calls `debuglog.Output` to print to the logger.
// Arguments are handled in the manner of fmt.Print
func Debug(v ...interface{}) {
if debuglog.Enabled {
debuglog.Output(2, fmt.Sprint(v...))
}
}
// Warnf calls `warnlog.Output` to print to the logger.
// Arguments are handled in the manner of fmt.Printf
func Warnf(format string, v ...interface{}) {
if warnlog.Enabled {
warnlog.Output(2, fmt.Sprintf(format, v...))
}
}
// Warn calls `warnlog.Output` to print to the logger.
// Arguments are handled in the manner of fmt.Print
func Warn(v ...interface{}) {
if warnlog.Enabled {
warnlog.Output(2, fmt.Sprint(v...))
}
}
// Errorf calls `errorlog.Output` to print to the logger.
// Arguments are handled in the manner of fmt.Printf
func Errorf(format string, v ...interface{}) {
if errorlog.Enabled {
errorlog.Output(2, fmt.Sprintf(format, v...))
}
}
// Error calls `errorlog.Output` to print to the logger.
// Arguments are handled in the manner of fmt.Print
func Error(v ...interface{}) {
if errorlog.Enabled {
errorlog.Output(2, fmt.Sprint(v...))
}
}
// Fatalf calls `fatallog.Output` to print to the logger.
// ANSI Red colour is added if the output is a character device
// Stack is also printed to `os.Stderr`
// Arguments are handled in the manner of fmt.Printf
func Fatalf(format string, v ...interface{}) {
if fatallog.Enabled {
if fatallog.SupportsColour {
fatallog.Output(2, "\x1b[31m"+fmt.Sprintf(format, v...)+"\x1b[0m")
} else {
fatallog.Output(2, fmt.Sprintf(format, v...))
}
fatallog.Output(2, fmt.Sprintf("Stack:\n%s\n", debug.Stack()))
}
if ExitOnFatalLog {
os.Exit(1)
}
}
// FatalfDepth calls `fatallog.Output` to print to the logger.
// `calldepth` is used to allow for better formatting in case of `check()`
// ANSI Red colour is added if the output is a character device
// Stack is also printed to `os.Stderr`
// Arguments are handled in the manner of fmt.Printf
func FatalfDepth(calldepth int, format string, v ...interface{}) {
if fatallog.Enabled {
if fatallog.SupportsColour {
fatallog.Output(calldepth, "\x1b[31m"+fmt.Sprintf(format, v...)+"\x1b[0m")
} else {
fatallog.Output(calldepth, fmt.Sprintf(format, v...))
}
fatallog.Output(calldepth, fmt.Sprintf("Stack:\n%s\n", debug.Stack()))
}
if ExitOnFatalLog {
os.Exit(1)
}
}
// Fatal calls `fatallog.Output` to print to the logger.
// ANSI Red colour is added if the output is a character device
// Stack is also printed to `os.Stderr`
// Arguments are handled in the manner of fmt.Print
func Fatal(v ...interface{}) {
if fatallog.Enabled {
if fatallog.SupportsColour {
fatallog.Output(2, "\x1b[31m"+fmt.Sprint(v...)+"\x1b[0m")
} else {
fatallog.Output(2, fmt.Sprint(v...))
}
fatallog.Output(2, fmt.Sprintf("Stack:\n%s\n", debug.Stack()))
}
if ExitOnFatalLog {
os.Exit(1)
}
}
// newLogger returns a new `awareLogger` for the given `level`.
// logs to `output`.
func newLogger(level string, output io.Writer) (al awareLogger) {
al.Enabled = true
fmtline := "|" + level + "| "
flags := log.LstdFlags
if level == "D" || level == "F" {
flags |= log.Lshortfile
}
// avoid colouring output if output is not an input device
al.SupportsColour = true
if file, ok := output.(*os.File); ok {
if !SupportsColour(file) {
al.SupportsColour = false
al.Logger = log.New(output, fmtline, flags)
}
}
if al.SupportsColour {
al.Logger = log.New(output, fmt.Sprintf("\x1b[%dm%s\x1b[0m", colourForLevel(level), fmtline), flags)
}
return
}
// SetLoggingLevel takes a level string and accordingly enables/disables loggers
// Supported values:
// "debug" / "5": all logging enabled
// "info" / "4": info and above enabled
// "warn" / "3": warn and above enabled
// "error" / "2": error and above enabled
// "fatal" / "1": only fatal enabled
// "disabled" / "none" / "off", "0": all loggers disabled
func SetLoggingLevel(level string) {
switch strings.ToLower(level) {
case "debug", "5":
debuglog.Enabled = true
infolog.Enabled = true
warnlog.Enabled = true
errorlog.Enabled = true
fatallog.Enabled = true
case "info", "4":
debuglog.Enabled = false
infolog.Enabled = true
warnlog.Enabled = true
errorlog.Enabled = true
fatallog.Enabled = true
case "warn", "3":
debuglog.Enabled = false
infolog.Enabled = false
warnlog.Enabled = true
errorlog.Enabled = true
fatallog.Enabled = true
case "error", "2":
debuglog.Enabled = false
infolog.Enabled = false
warnlog.Enabled = false
errorlog.Enabled = true
fatallog.Enabled = true
case "fatal", "1":
debuglog.Enabled = false
infolog.Enabled = false
warnlog.Enabled = false
errorlog.Enabled = false
fatallog.Enabled = true
case "disabled", "none", "off", "0":
debuglog.Enabled = false
infolog.Enabled = false
warnlog.Enabled = false
errorlog.Enabled = false
fatallog.Enabled = false
}
}
/*
===============================================================================
Misc
===============================================================================
*/
// ConcurrentlyWalkDir recursively traverses a directory and calls `onFile` for each found file inside a goroutine.
func ConcurrentlyWalkDir(dirPath string, onFile func(file string)) error {
guard := make(chan bool, config.OpenFileLimit) // limits number of concurrently open files
var files []string
wg := sync.WaitGroup{}
err := filepath.Walk(dirPath, func(filePath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
files = append(files, filePath)
return nil
})
if err != nil {
return err
}
// now goroutine each file
wg.Add(len(files))
m := sync.Mutex{}
for _, filePath := range files {
guard <- true // would block if guard channel is already filled
go func(path string) {
defer wg.Done()
m.Lock()
onFile(path)
m.Unlock()
<-guard
}(filePath)
}
wg.Wait()
return nil
}
// GetImplementationUID generates a DICOM implementation UID from OpenDCMRootUID and OpenDCMVersion
// NOTE: OpenDCM Implementation UIDs conform to the format:
// <<ROOT>>.<<VERSION>>.<<InstanceType>>
// Where ROOT = OpenDCMRootUID, VERSION = OpenDCMVersion, InstanceType= (1 for synthetic data, 0 for others)
func GetImplementationUID(synthetic bool) string {
instanceType := "0"
if synthetic {
instanceType = "1"
}
return fmt.Sprintf("%s%s.%s", OpenDCMRootUID, OpenDCMVersion, instanceType)
}
// NewRandInstanceUID generates a DICOM random instance UID from OpenDCMRootUID
func NewRandInstanceUID() (string, error) {
prefix := OpenDCMRootUID
max := big.Int{}
max.SetString(strings.Repeat("9", 64-len(prefix)), 10)
randval, err := rand.Int(rand.Reader, &max)
if err != nil {
return "", err
}
return fmt.Sprintf("%s%d", prefix, randval), nil
}