-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
109 lines (82 loc) · 2.16 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
package main
import (
"fmt"
"io"
"log"
"math"
"os"
"sync"
)
const FileSize = 10000
func main() {
file, err := os.Create("/tmp/alilog.txt")
if err != nil {
log.Fatal("Error while trying to create file", err)
}
defer file.Close()
for i := 1; i < 10001; i++ {
fmt.Fprintf(file, "Hi, this is line number %v\n", i)
}
// Task3: call fetchAllLogs
fetchAllLogs()
}
func fetchLogs(logFilePath string, numberOfLines, offset int64, reverse bool) {
// Calculate the offset position and the fetch size
byteToRead, byteOffset := calcByteToReadAndOffset(numberOfLines, offset, reverse)
file, err := os.Open(logFilePath)
if err != nil {
log.Fatal(err.Error())
return
}
defer file.Close()
byteBuffer := make([]byte, byteToRead)
// Reads len(byteBuffer) bytes from the File starting at byteOffset.
fetchBytes, err := file.ReadAt(byteBuffer, byteOffset)
if err != nil {
if err != io.EOF {
log.Fatal("Error while trying to fetchLogs", err.Error())
return
}
}
fmt.Println(string(byteBuffer[:fetchBytes]))
}
func calcByteToReadAndOffset(numberOfLines, offset int64, reverse bool) (int64, int64) {
// Check reverse flag
if reverse {
offset = FileSize - numberOfLines - offset
}
// Calculate totalLines: sum of numberOfLines and offset
totalLines := numberOfLines + offset
byteOffset := offset * 25
byteToRead := totalLines * 25
// Calculate byteOffset and byteToRead by iterating the totalLines
// And add the delta bytes
// e.x. if offset = 13 and numberOfLines = 96
// byteOffset will be 342 (9*26 + 4*27)
// byteToRead will be 2602 (86*27 + 10*28)
for i := 0; totalLines > 0; i++ {
reduce := 9 * int64(math.Pow10(i))
byteOffset += offset
offset -= reduce
byteToRead += totalLines
totalLines -= reduce
if offset < 0 {
offset = 0
}
}
return byteToRead - byteOffset, byteOffset
}
func fetchAllLogs() {
const NumOfLinesChunk = 100
const NumOfRoutines = FileSize / NumOfLinesChunk
var wg sync.WaitGroup
wg.Add(NumOfRoutines)
for i := 0; i < NumOfRoutines; i++ {
go func(i int) {
defer wg.Done()
// Call fetchLogs
fetchLogs("/tmp/alilog.txt", NumOfLinesChunk, int64(NumOfLinesChunk*i), false)
}(i)
}
wg.Wait()
}