Skip to content

Commit c87ae22

Browse files
committed
Moved agent helper functions to separate file
1 parent a9033f8 commit c87ae22

File tree

1 file changed

+210
-0
lines changed

1 file changed

+210
-0
lines changed

locker/agent_functions.go

Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
package locker
2+
3+
import (
4+
"bufio"
5+
"crypto/sha256"
6+
"encoding/binary"
7+
"errors"
8+
"fmt"
9+
"io"
10+
"net"
11+
"os"
12+
"path/filepath"
13+
"strings"
14+
"vikingPingvin/locker/locker/messaging"
15+
"vikingPingvin/locker/locker/messaging/protobuf"
16+
17+
"github.com/rs/xid"
18+
"github.com/rs/zerolog/log"
19+
"google.golang.org/protobuf/proto"
20+
)
21+
22+
// If --file cli input is not null, parse file
23+
func parseAndSendMetaData(connection net.Conn, inputData *InputData) (fileInfo os.FileInfo, err error) {
24+
fileInfo, err = os.Stat(inputData.FilePath)
25+
if os.IsNotExist(err) {
26+
log.Error().Msgf("Parsing file Input error: %v", err)
27+
return fileInfo, err
28+
}
29+
inputData.FileHash = hashFile(inputData.FilePath)
30+
inputData.FileName = fileInfo.Name()
31+
32+
log.Info().
33+
Str("file name", fileInfo.Name()).
34+
Str("Namespace", fmt.Sprintf("%s/%s/%s", inputData.NameSpace, inputData.Project, inputData.JobID)).
35+
Str("size", fmt.Sprintf("%d", fileInfo.Size())).
36+
Str("hash", fmt.Sprintf("%v", inputData.FileHash)).
37+
Str("id", inputData.ID.String()).
38+
Msg("Artifact metadata parsing finished")
39+
40+
message, err := messaging.CreateMessage_FileMeta(
41+
inputData.ID.Bytes(),
42+
protobuf.MessageType_META,
43+
inputData.NameSpace,
44+
inputData.Project,
45+
inputData.JobID,
46+
inputData.FileName,
47+
inputData.FileHash)
48+
if err != nil {
49+
panic(err)
50+
}
51+
52+
// Send Metadata message
53+
log.Info().Msg("Sending MetaData Packet")
54+
messaging.SendProtoBufMessage(connection, message)
55+
56+
return fileInfo, err
57+
}
58+
59+
//func parseAndSendPayload(bytes *[]byte, numBytes int) {
60+
func parseAndSendPayload(connection net.Conn, inputData *InputData) {
61+
62+
f, err := os.Open(inputData.FilePath)
63+
defer f.Close()
64+
if err != nil {
65+
log.Error().Msgf("Cannot open file %s", inputData.FilePath)
66+
}
67+
68+
log.Info().Msg("Started sending Payload Packets...")
69+
reader := bufio.NewReader(f)
70+
isPayloadFinal := false
71+
72+
buffer := make([]byte, 1024)
73+
for {
74+
n, ioErr := reader.Read(buffer)
75+
if ioErr == io.EOF {
76+
isPayloadFinal = true
77+
// Send terminating payload protobuf message
78+
terminalMessage, err := messaging.CreateMessage_FilePackage(
79+
inputData.ID.Bytes(),
80+
protobuf.MessageType_PACKAGE,
81+
make([]byte, 1),
82+
isPayloadFinal,
83+
)
84+
if err != nil {
85+
log.Fatal().Msg("Fatal Error during payload protobuf assembly")
86+
}
87+
messaging.SendProtoBufMessage(connection, terminalMessage)
88+
break
89+
}
90+
91+
message, err := messaging.CreateMessage_FilePackage(
92+
inputData.ID.Bytes(),
93+
protobuf.MessageType_PACKAGE,
94+
(buffer)[:n],
95+
isPayloadFinal)
96+
97+
if err != nil {
98+
log.Fatal().Msg("Fatal Error during payload protobuf assembly")
99+
}
100+
101+
messaging.SendProtoBufMessage(connection, message)
102+
}
103+
log.Info().Msg("Finished sending Payload Packets...")
104+
}
105+
106+
// Given a valid file path, returns a SHA256 hash
107+
func hashFile(path string) (hash []byte) {
108+
f, err := os.Open(path)
109+
defer f.Close()
110+
if err != nil {
111+
log.Err(err).Msgf("Cannot open file %s", path)
112+
}
113+
114+
hasher := sha256.New()
115+
if _, err := io.Copy(hasher, f); err != nil {
116+
log.Err(err).Msg("Error calculating SHA256 Hash")
117+
}
118+
return hasher.Sum(nil)
119+
}
120+
121+
func listenForACK(connection net.Conn, inputData *InputData) {
122+
123+
// TODO: Make into const in message_handler (also server.go)
124+
// sizePrefix is 4 bytes protobug message size
125+
sizePrefix := make([]byte, 4)
126+
127+
_, _ = io.ReadFull(connection, sizePrefix)
128+
protoLength := int(binary.BigEndian.Uint32(sizePrefix))
129+
130+
ackPacketRaw := make([]byte, protoLength)
131+
_, _ = io.ReadFull(connection, ackPacketRaw)
132+
genericProto := &protobuf.LockerMessage{}
133+
if err := proto.Unmarshal(ackPacketRaw, genericProto); err != nil {
134+
log.Err(err).Msg("Error during unmarshalling")
135+
}
136+
137+
if genericProto.GetAck().ProtoReflect().IsValid() {
138+
ackPacket := genericProto.GetAck()
139+
140+
serverResult := ackPacket.GetServerSuccess()
141+
ackID, _ := xid.FromBytes(ackPacket.GetId())
142+
if ackID != inputData.ID {
143+
log.Warn().
144+
Str("respone_id", ackID.String()).
145+
Str("original_id", inputData.ID.String()).
146+
Msg("Response ID mismatch.")
147+
}
148+
149+
log.Info().
150+
Str("id_back", ackID.String()).
151+
Msgf("ACK packet recieved from server with success flag: %v", serverResult)
152+
}
153+
}
154+
155+
// Parse raw CLI input parameters to internal data structures
156+
func parseInputArguments() []*InputData {
157+
var err error
158+
var inputPath string
159+
const inputPathSeparator = ","
160+
161+
if len(InputArgPath) == 0 {
162+
err = errors.New("--file empty")
163+
log.Err(err).Str("agent", "parseInputArguments").Msgf("No input file was given.")
164+
}
165+
if len(InputArgNamespace) == 0 {
166+
err = errors.New("--namespace empty")
167+
log.Err(err).Str("agent", "parseInputArguments").Msgf("No input namespace was given.")
168+
}
169+
if err != nil {
170+
os.Exit(1)
171+
}
172+
173+
//
174+
// Store information about Namespace, Project and Job-ID
175+
fullNameSpace := InputArgNamespace
176+
namePaths := strings.Split(fullNameSpace, "/")
177+
if len(namePaths) != 3 {
178+
err = errors.New("Namespace must contain 3 values separated by '/'")
179+
log.Err(err).Msg("Namespace values not valid")
180+
os.Exit(1)
181+
}
182+
183+
//
184+
// dataArray contains an *InputData, len(inputPathSlice) times
185+
inputPathSlice := strings.Split(InputArgPath, inputPathSeparator)
186+
dataArray := make([]*InputData, len(inputPathSlice))
187+
188+
for i, path := range inputPathSlice {
189+
if !filepath.IsAbs(path) {
190+
cwd, err := os.Getwd()
191+
if err != nil {
192+
log.Err(err).Msg("Error during CWD PATH parsing")
193+
os.Exit(1)
194+
}
195+
log.Debug().Msgf("Relative path of input: %s", path)
196+
inputPath = filepath.Join(cwd, path)
197+
198+
}
199+
200+
dataArray[i] = &InputData{
201+
FilePath: inputPath,
202+
NameSpace: namePaths[0],
203+
Project: namePaths[1],
204+
JobID: namePaths[2],
205+
ID: xid.New(),
206+
}
207+
}
208+
209+
return dataArray
210+
}

0 commit comments

Comments
 (0)