Skip to content

Commit

Permalink
update handlers and registry adapters
Browse files Browse the repository at this point in the history
Signed-off-by: bupd <[email protected]>
  • Loading branch information
bupd committed Jul 24, 2024
1 parent 98ce4d9 commit 010b8de
Show file tree
Hide file tree
Showing 14 changed files with 128 additions and 250 deletions.
10 changes: 2 additions & 8 deletions ground-control/internal/database/images.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions ground-control/internal/server/handleResponse.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ func (e *AppError) Error() string {
func WriteJSONResponse(w http.ResponseWriter, statusCode int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(data)
_ = json.NewEncoder(w).Encode(data)
}

// handle AppError and send structured JSON response.
// handle AppError and senda structured JSON response.
func HandleAppError(w http.ResponseWriter, err error) {
if appErr, ok := err.(*AppError); ok {
WriteJSONResponse(w, appErr.Code, appErr)
Expand Down
59 changes: 46 additions & 13 deletions ground-control/internal/server/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,15 @@ import (
"time"

"container-registry.com/harbor-satellite/ground-control/internal/database"
"container-registry.com/harbor-satellite/ground-control/reg"
"github.com/gorilla/mux"
)

type RegListParams struct {
Url string `json:"registry_url"`
UserName string `json:"username"`
Password string `json:"password"`
}
type GroupRequestParams struct {
GroupName string `json:"group_name"`
}
Expand Down Expand Up @@ -81,20 +87,24 @@ func (s *Server) healthHandler(w http.ResponseWriter, r *http.Request) {
func (s *Server) createGroupHandler(w http.ResponseWriter, r *http.Request) {
// Decode request body
var req GroupRequestParams
if err := DecodeRequestBody(r, req); err != nil {
if err := DecodeRequestBody(r, &req); err != nil {
HandleAppError(w, err)
return
}

params := database.CreateGroupParams{
GroupName: req.GroupName,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}

// Call the database query to create Group
result, err := s.dbQueries.CreateGroup(r.Context(), params)
if err != nil {
err = &AppError{
Message: err.Error(),
Code: http.StatusBadRequest,
}
HandleAppError(w, err)
return
}
Expand All @@ -104,7 +114,7 @@ func (s *Server) createGroupHandler(w http.ResponseWriter, r *http.Request) {

func (s *Server) createLabelHandler(w http.ResponseWriter, r *http.Request) {
var req LabelRequestParams
if err := DecodeRequestBody(r, req); err != nil {
if err := DecodeRequestBody(r, &req); err != nil {
HandleAppError(w, err)
return
}
Expand All @@ -125,7 +135,7 @@ func (s *Server) createLabelHandler(w http.ResponseWriter, r *http.Request) {

func (s *Server) addImageHandler(w http.ResponseWriter, r *http.Request) {
var req ImageAddParams
if err := DecodeRequestBody(r, req); err != nil {
if err := DecodeRequestBody(r, &req); err != nil {
HandleAppError(w, err)
return
}
Expand Down Expand Up @@ -265,11 +275,11 @@ func (s *Server) assignImageToGroup(w http.ResponseWriter, r *http.Request) {
}

func (s *Server) GetImagesForSatellite(w http.ResponseWriter, r *http.Request) {
token, err := GetAuthToken(r)
if err != nil {
HandleAppError(w, err)
return
}
token, err := GetAuthToken(r)
if err != nil {
HandleAppError(w, err)
return
}
result, err := s.dbQueries.GetImagesForSatellite(r.Context(), token)
if err != nil {
log.Printf("Error: Failed to get image for satellite: %v", err)
Expand All @@ -283,11 +293,34 @@ func (s *Server) GetImagesForSatellite(w http.ResponseWriter, r *http.Request) {
func (s *Server) listGroupHandler(w http.ResponseWriter, r *http.Request) {
result, err := s.dbQueries.ListGroups(r.Context())
if err != nil {
HandleAppError(w, err)
HandleAppError(w, err)
return
}

WriteJSONResponse(w, http.StatusOK, result)
WriteJSONResponse(w, http.StatusOK, result)
}

func (s *Server) regListHandler(w http.ResponseWriter, r *http.Request) {
username := r.URL.Query().Get("username")
password := r.URL.Query().Get("password")
url := r.URL.Query().Get("url")

if url == "" {
err := &AppError{
Message: "Missing URL in Request",
Code: http.StatusBadRequest,
}
HandleAppError(w, err)
return
}

result, err := reg.FetchRepos(username, password, url)
if err != nil {
HandleAppError(w, err)
return
}

WriteJSONResponse(w, http.StatusOK, result)
}

func (s *Server) getGroupHandler(w http.ResponseWriter, r *http.Request) {
Expand All @@ -300,7 +333,7 @@ func (s *Server) getGroupHandler(w http.ResponseWriter, r *http.Request) {
return
}

WriteJSONResponse(w, http.StatusOK, result)
WriteJSONResponse(w, http.StatusOK, result)
}

// creates a unique random API token of the specified length in bytes.
Expand Down
6 changes: 4 additions & 2 deletions ground-control/internal/server/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ func (s *Server) RegisterRoutes() http.Handler {
r.HandleFunc("/ping", s.Ping).Methods("GET")
r.HandleFunc("/health", s.healthHandler).Methods("GET")

// Ground Control interface
r.HandleFunc("/registry/list", s.regListHandler).Methods("GET")

// Ground Control interface
r.HandleFunc("/group/list", s.listGroupHandler).Methods("GET")
r.HandleFunc("/group/{group}", s.getGroupHandler).Methods("GET")

Expand All @@ -29,7 +31,7 @@ func (s *Server) RegisterRoutes() http.Handler {

r.HandleFunc("/satellite/images", s.GetImagesForSatellite).Methods("GET")

// Satellite based routes
// Satellite based routes
// r.HandleFunc("/images", s.getImageListHandler).Methods("GET")
// r.HandleFunc("/images", s.addImageListHandler).Methods("POST")
// r.HandleFunc("/group", s.deleteGroupHandler).Methods("DELETE")
Expand Down
1 change: 0 additions & 1 deletion ground-control/internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ func NewServer() *http.Server {
log.Fatalf("Error in sql: %v", err)
}


dbQueries := database.New(db)

NewServer := &Server{
Expand Down
Binary file removed ground-control/main
Binary file not shown.
3 changes: 2 additions & 1 deletion ground-control/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"log"

"container-registry.com/harbor-satellite/ground-control/internal/server"
_ "github.com/joho/godotenv/autoload"
Expand All @@ -13,6 +14,6 @@ func main() {
fmt.Printf("Ground Control running on port %s\n", server.Addr)
err := server.ListenAndServe()
if err != nil {
panic(fmt.Sprintf("cannot start server: %s", err))
log.Fatalf("cannot start server: %s", err)
}
}
66 changes: 66 additions & 0 deletions ground-control/reg/adapter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package reg

import (
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
)

type AppError struct {
Message string `json:"message"`
Code int `json:"code"`
}
type Image struct {
Digest string
Name string
}

type TagListResponse struct {
Name string `json:"name"`
Tags []string `json:"tags"`
}

func FetchRepos(username, password, url string) ([]string, error) {
// Sample Data
// username := "admin"
// password := "Harbor12345"
// url := "https://demo.goharbor.io"

url = url + "/v2/_catalog?n=1000"

req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %v", err)
}

// Encode credentials for Basic Authentication
auth := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
req.Header.Set("Authorization", "Basic "+auth)

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to make request: %v", err)
}
defer resp.Body.Close()

// Check the response status code
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch catalog: %s", resp.Status)
}

// Read the response body and decode JSON
var result map[string][]string
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("failed to unmarshal JSON response: %w", err)
}

// Extract the list of repositories
repos, ok := result["repositories"]
if !ok {
return nil, fmt.Errorf("repositories not found in response")
}

return repos, nil
}
80 changes: 0 additions & 80 deletions ground-control/reg/adapter/adapter.go

This file was deleted.

22 changes: 0 additions & 22 deletions ground-control/reg/adapter/adapter_test.go

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package main
package reg

import (
"context"
"testing"
)

func BenchmarkListRepos(b *testing.B) {
func BenchmarkFetchRepos(b *testing.B) {
for i := 0; i < b.N; i++ {
ListRepos(context.Background())
FetchRepos("admin", "Harbor12345", "https://demo.goharbor.io")
}
}

Expand All @@ -19,4 +18,3 @@ func BenchmarkListRepos(b *testing.B) {
// BenchmarkListRepos-12 1071 1028679 ns/op
// PASS
// ok container-registry.com/harbor-satellite/ground-control/reg 2.237s

Loading

0 comments on commit 010b8de

Please sign in to comment.