Skip to content

Commit

Permalink
Automated commit by Forgejo CI/CD [v1.5.4] - Personal CI/CD Bot
Browse files Browse the repository at this point in the history
  • Loading branch information
poniatowski-bot committed Aug 6, 2024
1 parent f7ab823 commit b9de391
Show file tree
Hide file tree
Showing 12 changed files with 199 additions and 9 deletions.
8 changes: 4 additions & 4 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
## [1.5.2] - 28-07-2024
### Updated
- made the config initialization more visual (orange for default and green for configured)
- fixed a bug, where it only fetched the code and not merge it (ala pull), I renamed the private function from gitFetcher() to gitPull(), instead of creating a private pull function to be called in gitFetcher()
## [1.5.4] - 05-08-2024
### Update
- added git dir check in gitClone, as the first output makes it look horrible
- adding whitespace... for those who are "idiomatically" inclined and finds it hard to read
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.5.2
1.5.4
14 changes: 14 additions & 0 deletions cmd/zehd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,16 @@ import (
func main() {
isReady := &atomic.Value{}
isReady.Store(false)

// Starting liveness probe
fmt.Printf(" Starting liveness probe...")
http.HandleFunc("/k8s/api/health", kubernetes.Healthz)
fmt.Println(" Done.")

// cloning repo from git source, if specified.
fmt.Println(" Checking git repo:")
fmt.Printf(" Cloning")

if len(pkg.GitLink) == 0 {
fmt.Printf("... Skipped.\n")
} else {
Expand All @@ -41,6 +44,7 @@ func main() {
fmt.Println(" Done.")
}
}

// init caching via go func(){check files for changes and figure out a way to pass them to handler}
fmt.Printf(" Building and Caching templates...")
cache := &caching.Pages{}
Expand All @@ -59,6 +63,7 @@ func main() {
}
}()
fmt.Println(" Done.")

// JS and CSS handling/serving
fmt.Printf(" Serving Static paths:\n")
fmt.Printf(" CSS...")
Expand All @@ -68,49 +73,58 @@ func main() {
} else {
fmt.Println(" Disabled.")
}

fmt.Printf(" JS... ")
if pkg.Javascript != pkg.Disable {
http.Handle("/"+pkg.Javascript+"/", http.StripPrefix("/"+pkg.Javascript+"/", http.FileServer(http.Dir(pkg.TemplatesDir+pkg.Javascript))))
fmt.Println(" Done.")
} else {
fmt.Println(" Disabled.")
}

fmt.Printf(" Images... ")
if pkg.Images != pkg.Disable {
http.Handle("/"+pkg.Images+"/", http.StripPrefix("/"+pkg.Images+"/", http.FileServer(http.Dir(pkg.TemplatesDir+pkg.Images))))
fmt.Println(" Done.")
} else {
fmt.Println(" Disabled.")
}

fmt.Printf(" Downloads... ")
if pkg.Downloads != pkg.Disable {
http.Handle("/"+pkg.Downloads+"/", http.StripPrefix("/"+pkg.Downloads+"/", http.FileServer(http.Dir(pkg.TemplatesDir+pkg.Downloads))))
fmt.Println(" Done.")
} else {
fmt.Println(" Disabled.")
}

// Initialize the database and determine if collector should be enabled
fmt.Printf(" Initializing Database...")
errEnv := godotenv.Load("/usr/local/env/.env")
if errEnv != nil {
boillog.LogIt("DatabaseExists", "ERROR", "error loading .env variables")
}

pkg.CollectionError = backendconnector.DatabaseInit()
if pkg.CollectionError != nil {
log.Println(" Failed.")
boillog.LogIt("Main", "WARNING", "Failed to initialize database, data will not be collected.")
} else {
fmt.Println(" Done.")
}

// Page serving section
fmt.Printf(" Initializing Routes...")
http.HandleFunc("/favicon.ico", pkg.FaviconHandler) // favicon
http.HandleFunc("/", cache.HandlerFunc)
fmt.Println(" Done.")

// Starting readiness probe
fmt.Printf(" Starting readiness probe...")
http.HandleFunc("/k8s/api/ready", kubernetes.Readyz(isReady))
fmt.Println(" Done.")

// Starting server
fmt.Printf(" Starting HTTP server on %v port %v...\n", env.EnvHostname(), strings.TrimLeft(env.EnvPort(), ":"))
fmt.Println("<======================================================================================>")
err := http.ListenAndServe(env.EnvPort(), nil)
Expand Down
22 changes: 22 additions & 0 deletions pkg/backendconnector/backendConnector.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ import (
// DatabaseInit Initialize the database with tables, if the check returns false
func DatabaseInit() error {
defer boillog.TrackTime("db-init", time.Now())

var databaseInfo DatabaseExistsInfo
databaseInfo.DatabaseExists()

if databaseInfo.Tables == "exists" {
boillog.LogIt("DatabaseInit", "INFO", "database already exists")
} else {
Expand Down Expand Up @@ -50,17 +52,21 @@ func DatabaseInit() error {
// DatabaseExists Check if database exists and has existing tables
func (dbInfo *DatabaseExistsInfo) DatabaseExists() {
defer boillog.TrackTime("db-exists", time.Now())

backendURL := os.Getenv("BACKEND")

if len(backendURL) == 0 {
dbInfo.Connection = "no env var"
return
}

response, errHTTPGet := http.Get(backendURL + "/database/exist")
if errHTTPGet != nil {
dbInfo.Connection = "failed"
boillog.LogIt("DatabaseExists", "ERROR", "unable to reach backend on "+backendURL)
return
}

defer func() {
errClose := response.Body.Close()
if errClose != nil {
Expand All @@ -70,26 +76,35 @@ func (dbInfo *DatabaseExistsInfo) DatabaseExists() {

}
}()

body, _ := io.ReadAll(response.Body)

dbInfo.Tables = string(body) // TODO reading results from here

boillog.LogIt("DatabaseInit", "INFO", "received: \""+dbInfo.Tables+"\" from "+backendURL+"(GET request)")
}

func (dbInfo *DatabaseExistsInfo) DatabaseCreate() {
// create post request
defer boillog.TrackTime("create-db", time.Now())

backendURL := os.Getenv("BACKEND")

if len(backendURL) == 0 {
dbInfo.Connection = "no env var"
boillog.LogIt("DatabaseCreate", "WARNING", "no backend to send data to, please add backend url as env variable")
return
}

dbInfo.Tables = "create"

req, _ := json.Marshal(dbInfo)

response, errHTTPGet := http.Post(backendURL+"/database/exist", "application/json", bytes.NewBuffer(req))
if errHTTPGet != nil {
boillog.LogIt("DatabaseCreate", "ERROR", "unable to reach backend")
}

defer func() {
errClose := response.Body.Close()
if errClose != nil {
Expand All @@ -101,30 +116,37 @@ func (dbInfo *DatabaseExistsInfo) DatabaseCreate() {
// DBConnector Function to insert request data into the database
func (rD *RequestData) DBConnector(waitGroup *sync.WaitGroup) {
defer boillog.TrackTime("db-connector", time.Now())

waitGroup.Add(1)

jsonToBackend, errMarshal := json.Marshal(rD)
if errMarshal != nil {
boillog.LogIt("DBConnector", "ERROR", "unable to marshal json request")
}

backendURL := os.Getenv("BACKEND")

if len(backendURL) == 0 {
boillog.LogIt("DBConnector", "WARNING", "no backend to send data to, please add backend url as env variable")
} else {
resp, errResp := http.Post(backendURL+"/api/collect", "application/json", bytes.NewBuffer(jsonToBackend))
if errResp != nil {
boillog.LogIt("DBConnector", "ERROR", "unable to send json request, response error received")
}

defer func() {
errClose := resp.Body.Close()
if errClose != nil {
boillog.LogIt("DBConnector", "ERROR", "unable to close response body")
}
}()

if resp.StatusCode == 200 {
log.Println("User data sent to database successfully")
} else if resp.StatusCode == 500 {
boillog.LogIt("DBConnector", "WARNING", "no backend to send data to, please add backend url as env variable")
}
}

waitGroup.Done()
}
20 changes: 20 additions & 0 deletions pkg/caching/caching.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,54 +15,74 @@ import (
// CachePages Method that walks the specified or default directories and caches the templates
func (pages *Pages) CachePages() error {
defer boillog.TrackTime("cacher", time.Now())

if len(pkg.GitLink) != 0 {
err := Git("refresh")
if err != nil {
boillog.LogIt("CachePages", "ERROR", err.Error())
return err
}

return nil
}

errchdir := os.Chdir(pkg.TemplatesDir + pkg.TemplateType)
if errchdir != nil {
boillog.LogIt("cachepages", "error", "chdir returned an error: "+fmt.Sprintln(errchdir))
}

err := filepath.WalkDir(pkg.TemplatesDir+pkg.TemplateType, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}

if d.IsDir() {
return nil
}

pathtoremove := pkg.TemplatesDir + pkg.TemplateType

indextoremove := strings.Index(path, pathtoremove)
if indextoremove == -1 {
boillog.LogIt("cachepages", "error", "directory not found")
}

croppedtemplatepath := strings.TrimPrefix(path[indextoremove+len(pathtoremove):], "/")

var filetype string

switch filepath.Ext(path) {
case ".gohtml":
filetype = ".gohtml"

case ".html":
filetype = ".html"

case ".md":
filetype = ".md"

case ".org":
filetype = ".org"

default:
filetype = "invalid"
}

name := strings.TrimSuffix(croppedtemplatepath, filepath.Ext(path))

tmpl, err := templateBuilder(croppedtemplatepath, filetype)
if err != nil {
return fmt.Errorf("failed to build template for file %q: %v", path, err)
}

pages.RouteMap[name] = tmpl

return nil
})
if err != nil {
boillog.LogIt("cachepages", "error", "walkdir returned an error: "+fmt.Sprintln(err))
return err
}

return nil
}
Loading

0 comments on commit b9de391

Please sign in to comment.