TODO Move this to a repository that uses flat files for now but potentially a database in the future createLogFile makes a new log file for the provided Agent ID for future log messages
(id uuid.UUID)
| 72 | // TODO Move this to a repository that uses flat files for now but potentially a database in the future |
| 73 | // createLogFile makes a new log file for the provided Agent ID for future log messages |
| 74 | func createLogFile(id uuid.UUID) (agentLog *os.File, err error) { |
| 75 | current, err := os.Getwd() |
| 76 | if err != nil { |
| 77 | slog.Error(err.Error()) |
| 78 | return nil, fmt.Errorf("there was an error getting the current working directory: %s", err) |
| 79 | } |
| 80 | dir := filepath.Join(current, "data", "agents") |
| 81 | |
| 82 | // Create a directory for the new agent's files |
| 83 | if _, err = os.Stat(filepath.Join(dir, id.String())); os.IsNotExist(err) { |
| 84 | err = os.MkdirAll(filepath.Join(dir, id.String()), 0750) |
| 85 | if err != nil { |
| 86 | return nil, fmt.Errorf("pkg/agents.createLogFile(): there was an error creating a directory for agent %s: %s", id, err) |
| 87 | } |
| 88 | // Create the agent's log file |
| 89 | agentLog, err = os.Create(filepath.Join(dir, id.String(), "log.txt")) // #nosec G304 Users can include any file they want |
| 90 | if err != nil { |
| 91 | return nil, fmt.Errorf("pkg/agents.createLogFile(): there was an error creating the log.txt file for agent %s: %s", id, err) |
| 92 | } |
| 93 | |
| 94 | // Change the file's permissions |
| 95 | err = os.Chmod(agentLog.Name(), 0600) |
| 96 | if err != nil { |
| 97 | return nil, fmt.Errorf("pkg/agents.createLogFile(): there was an error changing the agent's log file permissions for %s: %s", id, err) |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | // Open agent's log file for writing |
| 102 | agentLog, err = os.OpenFile(filepath.Clean(filepath.Join(dir, id.String(), "log.txt")), os.O_APPEND|os.O_WRONLY, 0600) |
| 103 | if err != nil { |
| 104 | return nil, fmt.Errorf("pkg/agents.createLogFile(): there was an error opening the log file for agent %s: %s", id, err) |
| 105 | } |
| 106 | return |
| 107 | } |
| 108 | |
| 109 | // Alive returns true if the Agent is actively in use and false if the agent has been killed or removed |
| 110 | func (a *Agent) Alive() bool { |