From d2d08cecf4746a53df305fb67468919ef9657836 Mon Sep 17 00:00:00 2001 From: Emile Date: Thu, 7 Feb 2019 02:45:33 +0100 Subject: new model, see the wiki for a description how this all works --- README.md | 123 ++++++++++-------------------------- db_actions.go | 153 +++++++++++++++++--------------------------- docker-compose.yml | 12 +++- export.go | 40 ------------ import.go | 94 ---------------------------- manage.go | 181 ----------------------------------------------------- metrics.go | 45 ------------- update.go | 27 -------- 8 files changed, 99 insertions(+), 576 deletions(-) delete mode 100644 export.go delete mode 100644 import.go delete mode 100644 manage.go delete mode 100644 metrics.go delete mode 100644 update.go diff --git a/README.md b/README.md index 7e8b243..0e9eeca 100644 --- a/README.md +++ b/README.md @@ -18,96 +18,39 @@ This Repo contains the main "database" running an http-api exposing the quadtree | `"/export/{treeindex}"` | Export the selected tree to `db/{treeindex}.json` | | | `"/fastinsert/{filename}"` | Insert the selected file into a new tree | | - -## Files - -Simple description of each individual function - -### export.go - -``` -func export(treeindex int64) error { - // exports the tree with the given tree index by writing it's json - // to /exports/{treeindex}.json -} - -func exportHandler(w http.ResponseWriter, r *http.Request) { - // handles request to /export/{treeindex} and uses the export function - // to export the selected tree -} -``` - -### update.go - -``` -func updateCenterOfMassHandler(w http.ResponseWriter, r *http.Request) { - // updates the center of mass of every node in the tree width the given index -} - -func updateTotalMassHandler(w http.ResponseWriter, r *http.Request) { - // updates the total mass of every node in the tree with the given index -} -``` - -### import.go - +## Tables + +### nodes + +```postgresql +-- Table: public.nodes + +-- DROP TABLE public.nodes; + +CREATE TABLE public.nodes +( + node_id bigint NOT NULL DEFAULT nextval('nodes_node_id_seq'::regclass), + box_center_x numeric, + box_center_y numeric, + box_width numeric, + center_of_mass_x numeric, + center_of_mass_y numeric, + total_mass numeric, + depth numeric, + star_id bigint, + "subnode_A" bigint, + "subnode_B" bigint, + "subnode_C" bigint, + "subnode_D" bigint, + CONSTRAINT nodes_pkey PRIMARY KEY (node_id) +) +WITH ( + OIDS = FALSE +) +TABLESPACE pg_default; + +ALTER TABLE public.nodes + OWNER to postgres; ``` -func fastInsertHandler(w http.ResponseWriter, r *http.Request) { - // creates a new tree by reading from /db/{filename}.json and inserting the tree - // from that file into the treeArray - // The function returns the index in which it inserted the tree -} -``` - -### manage.go -``` -func newTreeHandler(w http.ResponseWriter, r *http.Request) { - // creates a new empty tree with the given width -} - -func newTree(width float64) []byte { - // creates a new tree and returns it json formatted as a bytestring -} - -func printAllHandler(w http.ResponseWriter, r *http.Request) { - // prints all the trees in the treeArray in json format -} - -func insertStarHandler(w http.ResponseWriter, r *http.Request) { - // inserts the given star into the tree -} - -func starlistHandler(w http.ResponseWriter, r *http.Request) { - // lists all the stars in the given tree -} - -func dumptreeHandler(w http.ResponseWriter, r *http.Request) { - // returns the tree with the given index in json format -} -``` - -### metrics.go - -``` -func metricHandler(w http.ResponseWriter, r *http.Request) { - // locally published the databases metrics -} - -func pushMetricsNumOfStars(host string, treeindex int64) { - // pushes the metrics of the tree with the given index to the metric-bundler - // using the given host and -} -``` - -### update.go - -``` -func updateCenterOfMassHandler(w http.ResponseWriter, r *http.Request) { - // updates the center of mass of every node in the tree with the given index -} -func updateTotalMassHandler(w http.ResponseWriter, r *http.Request) { - // updates the total mass in the tree with the given index -} -``` \ No newline at end of file diff --git a/db_actions.go b/db_actions.go index 264d707..2d38fbc 100644 --- a/db_actions.go +++ b/db_actions.go @@ -56,7 +56,7 @@ func newTree(db *sql.DB, width float64) { var currentMaxRootID int64 err := db.QueryRow(query).Scan(¤tMaxRootID) if err != nil { - log.Fatalf("[E] max root id query: %v", err) + log.Fatalf("[E] max root id query: %v\n\t\t\t query: %s\n", err, query) } // build the query creating a new node @@ -65,7 +65,7 @@ func newTree(db *sql.DB, width float64) { // execute the query _, err = db.Query(query) if err != nil { - log.Fatalf("[E] insert new node query: %v", err) + log.Fatalf("[E] insert new node query: %v\n\t\t\t query: %s\n", err, query) } } @@ -80,7 +80,7 @@ func insertStar(db *sql.DB, star structs.Star2D, index int64) { var id int64 err := db.QueryRow(query).Scan(&id) if err != nil { - log.Fatalf("[E] Get root node id query: %v", err) + log.Fatalf("[E] Get root node id query: %v\n\t\t\t query: %s\n", err, query) } // insert the star into the tree (using it's ID) starting at the root @@ -105,7 +105,7 @@ func insertIntoStars(star structs.Star2D, db *sql.DB) int64 { var starID int64 err := db.QueryRow(query).Scan(&starID) if err != nil { - log.Fatalf("[E] insert query: %v", err) + log.Fatalf("[E] insert query: %v\n\t\t\t query: %s\n", err, query) } return starID @@ -139,7 +139,7 @@ func insertIntoTree(starID int64, db *sql.DB, nodeID int64) { // if the node is a leaf and does not contain a star // insert the star into the node and subdivide it if isLeaf == true && containsStar == false { - log.Println("[~] isLeaf == true && containsStar == false") + log.Printf("[~] isLeaf == true && containsStar == false \t\t %d", starID) directInsert(starID, db, nodeID) subdivide(db, nodeID) } @@ -148,50 +148,29 @@ func insertIntoTree(starID int64, db *sql.DB, nodeID int64) { // insert the preexisting star into the correct subtree // insert the new star into the subtree if isLeaf == false && containsStar == true { - log.Println("[~] isLeaf == false && containsStar == true") + log.Printf("[~] isLeaf == false && containsStar == true \t\t %d", starID) // Stage 1: Inserting the blocking star - log.Println("[i] Getting the blocking-Star-ID") - blockingStar := getBlockingStar(db, nodeID) - log.Println("[i] Done") + blockingStarID := getBlockingStarID(db, nodeID) // get the id of the star blocking the node + blockingStar := getStar(db, blockingStarID) // get the actual star + blockingStarQuadrant := quadrant(db, blockingStar, nodeID) // find out in which quadrant it belongs + quadrantNodeID := getQuadrantNodeID(db, nodeID, blockingStarQuadrant) // get the nodeID of that quadrant + insertIntoTree(blockingStarID, db, quadrantNodeID) // insert the star into that node + removeStarFromNode(db, nodeID) // remove the blocking star from the node it was blocking - log.Println("[i] Getting the quadrant the blocking star is inside of") - blockingStarQuadrant := quadrant(db, blockingStar, nodeID) - log.Println("[i] Done") - - log.Println("[i] Getting the quadrant node id") - quadrantNodeID := getQuadrantNodeID(db, nodeID, blockingStarQuadrant) - log.Println("[i] Done") - - log.Printf("[i] Inserting the star into the new quadrant %d (%d)", quadrantNodeID, blockingStarQuadrant) - insertIntoTree(starID, db, quadrantNodeID) - log.Println("[i] Done") - - removeStarFromNode(db, nodeID) - - log.Println("[i] Getting the blocking-Star-ID") - star := getStar(db, starID) - log.Println("[i] Done") - - // Stage 2: Inserting the star that should originally be inserted - log.Println("[i] Getting the quadrant the star is inside of") - starQuadrant := quadrant(db, star, nodeID) - log.Println("[i] Done") - - log.Println("[i] Getting the quadrant node id") - quadrantNodeID = getQuadrantNodeID(db, nodeID, starQuadrant) - log.Println("[i] Done") - - log.Printf("[i] Inserting the star into the new quadrant %d (%d)", quadrantNodeID, starQuadrant) - insertIntoTree(starID, db, quadrantNodeID) - log.Println("[i] Done") + // Stage 1: Inserting the actual star + insertIntoTree(starID, db, nodeID) } // if the node is not a leaf and does not contain a star // insert the new star into the subtree if isLeaf == false && containsStar == false { - log.Println("[~] isLeaf == false && containsStar == false") - directInsert(starID, db, nodeID) + log.Printf("[~] isLeaf == false && containsStar == false \t\t %d", starID) + + star := getStar(db, starID) // get the actual star + starQuadrant := quadrant(db, star, nodeID) // find out in which quadrant it belongs + quadrantNodeID := getQuadrantNodeID(db, nodeID, starQuadrant) // get the if of that quadrant + insertIntoTree(starID, db, quadrantNodeID) // insert the star into that quadrant } } @@ -203,7 +182,7 @@ func containsStar(db *sql.DB, id int64) bool { query := fmt.Sprintf("SELECT star_id FROM nodes WHERE node_id=%d", id) err := db.QueryRow(query).Scan(&starID) if err != nil { - log.Fatalf("[E] containsStar query: %v", err) + log.Fatalf("[E] containsStar query: %v\n\t\t\t query: %s\n", err, query) } if starID != 0 { @@ -220,7 +199,7 @@ func isLeaf(db *sql.DB, nodeID int64) bool { query := fmt.Sprintf("SELECT COALESCE(isleaf, FALSE) FROM nodes WHERE node_id=%d", nodeID) err := db.QueryRow(query).Scan(&isLeaf) if err != nil { - log.Fatalf("[E] isLeaf query: %v", err) + log.Fatalf("[E] isLeaf query: %v\n\t\t\t query: %s\n", err, query) } if isLeaf == true { @@ -239,7 +218,7 @@ func directInsert(starID int64, db *sql.DB, nodeID int64) { // Execute the query _, err := db.Query(query) if err != nil { - log.Fatalf("[E] directInsert query: %v", err) + log.Fatalf("[E] directInsert query: %v\n\t\t\t query: %s\n", err, query) } } @@ -250,8 +229,8 @@ func subdivide(db *sql.DB, nodeID int64) { boxCenter := getBoxCenter(db, nodeID) originalDepth := getNodeDepth(db, nodeID) - log.Printf("[i] original box width: %f", boxWidth) - log.Printf("[i] original box center: %f", boxCenter) + log.Printf("[i] original box width: %f\n", boxWidth) + log.Printf("[i] original box center: %f\n", boxCenter) // calculate the new positions newPosX := boxCenter[0] + (boxWidth / 2) @@ -260,8 +239,8 @@ func subdivide(db *sql.DB, nodeID int64) { newNegY := boxCenter[1] - (boxWidth / 2) newWidth := boxWidth / 2 - log.Printf("[i] new box width: %f", newWidth) - log.Printf("[i] new box center: [±%f, ±%f]", newPosX, newPosY) + log.Printf("[i] new box width: %f\n", newWidth) + log.Printf("[i] new box center: [±%f, ±%f]\n", newPosX, newPosY) // create new news with those positions newNodeIDA := newNode(db, newPosX, newPosY, newWidth, originalDepth+1) @@ -277,7 +256,7 @@ func subdivide(db *sql.DB, nodeID int64) { // Execute the query _, err := db.Query(query) if err != nil { - log.Fatalf("[E] subdivide query: %v", err) + log.Fatalf("[E] subdivide query: %v\n\t\t\t query: %s\n", err, query) } } @@ -288,7 +267,7 @@ func getBoxWidth(db *sql.DB, nodeID int64) float64 { query := fmt.Sprintf("SELECT box_width FROM nodes WHERE node_id=%d", nodeID) err := db.QueryRow(query).Scan(&boxWidth) if err != nil { - log.Fatalf("[E] getBoxWidth query: %v", err) + log.Fatalf("[E] getBoxWidth query: %v\n\t\t\t query: %s\n", err, query) } return boxWidth @@ -303,14 +282,14 @@ func getBoxCenter(db *sql.DB, nodeID int64) []float64 { query := fmt.Sprintf("SELECT box_center FROM nodes WHERE node_id=%d", nodeID) err := db.QueryRow(query).Scan(&boxCenter) if err != nil { - log.Fatalf("[E] getBoxCenter query: %v", err) + log.Fatalf("[E] getBoxCenter query: %v\n\t\t\t query: %s\n", err, query) } boxCenterX, parseErr := strconv.ParseFloat("0", 64) boxCenterY, parseErr := strconv.ParseFloat("0", 64) if parseErr != nil { - log.Fatalf("[E] parse boxCenter: %v", err) - log.Fatalf("[E] parse boxCenter: %s", boxCenter) + log.Fatalf("[E] parse boxCenter: %v\n\t\t\t query: %s\n", err, query) + log.Fatalf("[E] parse boxCenter: %s\n", boxCenter) } boxCenterFloat := []float64{boxCenterX, boxCenterY} @@ -329,13 +308,13 @@ func newNode(db *sql.DB, posX float64, posY float64, width float64, depth int64) // execute the query err := db.QueryRow(query).Scan(&nodeID) if err != nil { - log.Fatalf("[E] newNode query: %v", err) + log.Fatalf("[E] newNode query: %v\n\t\t\t query: %s\n", err, query) } return nodeID } -func getBlockingStar(db *sql.DB, nodeID int64) structs.Star2D { +func getBlockingStarID(db *sql.DB, nodeID int64) int64 { // 1. get the star id from the node // 2. get the stars coordinates from the stars table // 3. pack the star and return it @@ -345,33 +324,10 @@ func getBlockingStar(db *sql.DB, nodeID int64) structs.Star2D { query := fmt.Sprintf("SELECT star_id FROM nodes WHERE node_id=%d", nodeID) err := db.QueryRow(query).Scan(&starID) if err != nil { - log.Fatalf("[E] getBlockingStar id query: %v", err) + log.Fatalf("[E] getBlockingStarID id query: %v\n\t\t\t query: %s\n", err, query) } - fmt.Printf("[i] Getting star with the id %d\n", starID) - - var x, y, vx, vy, m float64 - - // get the star from the stars table - query = fmt.Sprintf("SELECT x, y, vx, vy, m FROM stars WHERE star_id=%d", starID) - err = db.QueryRow(query).Scan(&x, &y, &vx, &vy, &m) - if err != nil { - log.Fatalf("[E] getBlockingStar star query: %v", err) - } - - star := structs.Star2D{ - C: structs.Vec2{ - X: x, - Y: y, - }, - V: structs.Vec2{ - X: vx, - Y: vy, - }, - M: m, - } - - return star + return starID } // deleteAll Stars deletes all the rows in the stars table @@ -383,7 +339,7 @@ func deleteAllStars(db *sql.DB) { // execute the query _, err := db.Query(query) if err != nil { - log.Fatalf("[E] deleteAllStars query: %v", err) + log.Fatalf("[E] deleteAllStars query: %v\n\t\t\t query: %s\n", err, query) } } @@ -396,7 +352,7 @@ func deleteAllNodes(db *sql.DB) { // execute the query _, err := db.Query(query) if err != nil { - log.Fatalf("[E] deleteAllStars query: %v", err) + log.Fatalf("[E] deleteAllStars query: %v\n\t\t\t query: %s\n", err, query) } } @@ -412,7 +368,7 @@ func getNodeDepth(db *sql.DB, nodeID int64) int64 { // Execute the query err := db.QueryRow(query).Scan(&depth) if err != nil { - log.Fatalf("[E] getNodeDepth query: %v", err) + log.Fatalf("[E] getNodeDepth query: %v \n\t\t\t query: %s\n", err, query) } return depth @@ -455,7 +411,7 @@ func getQuadrantNodeID(db *sql.DB, parentNodeID int64, quadrant int64) int64 { query := fmt.Sprintf("SELECT subnode[1], subnode[2], subnode[3], subnode[4] FROM nodes WHERE node_id=%d", parentNodeID) err := db.QueryRow(query).Scan(&a, &b, &c, &d) if err != nil { - log.Fatalf("[E] getQuadrantNodeID star query: %v", err) + log.Fatalf("[E] getQuadrantNodeID star query: %v \n\t\t\tquery: %s\n", err, query) } log.Printf("[o] %v", a) @@ -479,26 +435,16 @@ func getQuadrantNodeID(db *sql.DB, parentNodeID int64, quadrant int64) int64 { return -1 } -func removeStarFromNode(db *sql.DB, nodeID int64) { - - // build the query - query := fmt.Sprintf("UPDATE nodes SET star_id=0 WHERE node_id=%d", nodeID) - - // Execute the query - _, err := db.Query(query) - if err != nil { - log.Fatalf("[E] removeStarFromNode query: %v", err) - } -} - func getStar(db *sql.DB, starID int64) structs.Star2D { var x, y, vx, vy, m float64 + log.Printf("[i] getStar starID: %d", starID) + // get the star from the stars table query := fmt.Sprintf("SELECT x, y, vx, vy, m FROM stars WHERE star_id=%d", starID) err := db.QueryRow(query).Scan(&x, &y, &vx, &vy, &m) if err != nil { - log.Fatalf("[E] getStar star query: %v", err) + log.Fatalf("[E] getStar query: %v \n\t\t\tquery: %s\n", err, query) } star := structs.Star2D{ @@ -515,3 +461,16 @@ func getStar(db *sql.DB, starID int64) structs.Star2D { return star } + +func removeStarFromNode(db *sql.DB, nodeID int64) { + log.Printf("[i] Removing the star from the node with the id %d", nodeID) + + // build the query + query := fmt.Sprintf("UPDATE nodes SET star_id=0 WHERE node_id=%d", nodeID) + + // Execute the query + _, err := db.Query(query) + if err != nil { + log.Fatalf("[E] removeStarFromNode query: %v\n\t\t\t query: %s\n", err, query) + } +} diff --git a/docker-compose.yml b/docker-compose.yml index a268556..ed0c55b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,5 +1,13 @@ version: '3' services: - db: - build: . + postgresql: + image: postgres + volumes: + - db-data:/var/lib/postgresql/data + ports: + - "5432:5432" + +volumes: + db-data: + driver: local diff --git a/export.go b/export.go deleted file mode 100644 index 9cc67af..0000000 --- a/export.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strconv" - - "github.com/gorilla/mux" -) - -// export exports all the trees -func export(treeindex int64) error { - // Convert the data to json - jsonData, jsonMarshalerError := json.Marshal(treeArray[treeindex]) - if jsonMarshalerError != nil { - panic(jsonMarshalerError) - } - - // write the json formatted byte data to a file - err := ioutil.WriteFile(fmt.Sprintf("/exports/tree_%d.json", treeindex), jsonData, 0644) - if err != nil { - return err - } - return nil -} - -// export the selected tree to the selected file -func exportHandler(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - treeindex, _ := strconv.ParseInt(vars["treeindex"], 10, 0) - - err := export(treeindex) - if err != nil { - panic(err) - } - - _, _ = fmt.Fprintf(w, "Exportet Tree %d", treeindex) -} diff --git a/import.go b/import.go deleted file mode 100644 index c3c1e96..0000000 --- a/import.go +++ /dev/null @@ -1,94 +0,0 @@ -package main - -import ( - "encoding/csv" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "strconv" - "strings" - - "github.com/gorilla/mux" - - "git.darknebu.la/GalaxySimulator/structs" -) - -// fastInsertHandler gets a tree index and a filename and tries to read insert all the stars from the file into the tree -func fastInsertJSONHandler(w http.ResponseWriter, r *http.Request) { - // read the mux variables - vars := mux.Vars(r) - filename, _ := vars["filename"] - - // read the content using the given filename - content, readErr := ioutil.ReadFile(fmt.Sprintf("/db/%s", filename)) - if readErr != nil { - panic(readErr) - } - - // unmarshal the file content - tree := &structs.Node{} - jsonUnmarshalErr := json.Unmarshal(content, tree) - if jsonUnmarshalErr != nil { - panic(jsonUnmarshalErr) - } - - // append the tree to the treeArray - treeArray = append(treeArray, tree) - - // return the treeArray index the tree was inserted into (== the length of the array) - _, _ = fmt.Fprintln(w, len(treeArray)) -} - -func fastInsertListHandler(w http.ResponseWriter, r *http.Request) { - // read the mux variables - vars := mux.Vars(r) - filename, _ := vars["filename"] - treeindex, _ := strconv.ParseInt(vars["filename"], 10, 64) - - // read the content using the given filename - content, readErr := ioutil.ReadFile(fmt.Sprintf("/home/db/%s", filename)) - if readErr != nil { - panic(readErr) - } - - in := string(content) - reader := csv.NewReader(strings.NewReader(in)) - - for { - record, err := reader.Read() - if err == io.EOF { - break - } - if err != nil { - log.Println("------------------------") - log.Println("error:") - log.Println(record) - log.Println(err) - log.Println("------------------------") - } - fmt.Println(record) - - x, _ := strconv.ParseFloat(record[0], 64) - y, _ := strconv.ParseFloat(record[1], 64) - - fmt.Println("___________________") - fmt.Println(record[1]) - fmt.Println(y) - fmt.Println("___________________") - - star := structs.NewStar2D(structs.Vec2{x, y}, structs.Vec2{0, 0}, 42) - - fmt.Printf("Star: %v", star) - - err = treeArray[treeindex].Insert(star) - if err != nil { - log.Println(err) - errorCount[treeindex] += 1 - } - fmt.Printf("Inserted %v\n", star) - starCount[treeindex] += 1 - } -} diff --git a/manage.go b/manage.go deleted file mode 100644 index b7a5ce4..0000000 --- a/manage.go +++ /dev/null @@ -1,181 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "log" - "net/http" - "strconv" - - "github.com/gorilla/mux" - - "git.darknebu.la/GalaxySimulator/structs" -) - -// newTreeHandler creates a new tree -func newTreeHandler(w http.ResponseWriter, r *http.Request) { - // set the content type to json (looks fancy in firefox :D) - w.Header().Set("Content-Type", "application/json") - - fmt.Println("Creating a new tree") - - // get the star by parsing http-post parameters - errParseForm := r.ParseForm() // parse the POST form - if errParseForm != nil { // handle errors - panic(errParseForm) - } - - // default values - width := 100.0 - - // value from the user - userWidth, _ := strconv.ParseFloat(r.Form.Get("w"), 64) // bounding box width - log.Printf("width: %f", userWidth) - - // overwrite the default width - if userWidth != width { - width = userWidth - } - - jsonData := newTree(width) - - // return the new tree as json - _, _ = fmt.Fprintf(w, "%v", string(jsonData)) -} - -// newTree generates a new tree using the width it is given and returns it as json in an array of bytes -func newTree(width float64) []byte { - - // generate a new tree and add it to the treeArray - newTree := structs.NewRoot(width) - treeArray = append(treeArray, newTree) - starCount = append(starCount, 0) - - // convert the tree to json format - jsonData, jsonMarshalErr := json.Marshal(newTree) - if jsonMarshalErr != nil { - panic(jsonMarshalErr) - } - - return jsonData - -} - -// printAllHandler prints all the trees in the treeArray -func printAllHandler(w http.ResponseWriter, r *http.Request) { // set the content type to json (looks fancy in firefox :D) - w.Header().Set("Content-Type", "application/json") - - // Convert the data to json - jsonData, jsonMarshalerError := json.Marshal(treeArray) - if jsonMarshalerError != nil { - panic(jsonMarshalerError) - } - - // print the jsonData to the ResponseWriter - _, printTreeErr := fmt.Fprintf(w, "%v\n", string(jsonData)) - if printTreeErr != nil { - panic(printTreeErr) - } - - log.Printf("The printAll endpoint was accessed.\n") -} - -// insertStarHandler inserts a star into the given tree -func insertStarHandler(w http.ResponseWriter, r *http.Request) { - log.Println("The insert handler was accessed") - - // get the treeindex in which the star should be inserted into - vars := mux.Vars(r) - treeindex, _ := strconv.ParseInt(vars["treeindex"], 10, 0) - - // get the star by parsing http-post parameters - errParseForm := r.ParseForm() // parse the POST form - if errParseForm != nil { // handle errors - panic(errParseForm) - } - - // get the star coordinates - x, _ := strconv.ParseFloat(r.Form.Get("x"), 64) - y, _ := strconv.ParseFloat(r.Form.Get("y"), 64) - vx, _ := strconv.ParseFloat(r.Form.Get("vx"), 64) - vy, _ := strconv.ParseFloat(r.Form.Get("vy"), 64) - m, _ := strconv.ParseFloat(r.Form.Get("m"), 64) - - log.Printf("treeindex: %d", treeindex) - log.Printf("x: %f", x) - log.Printf("y: %f", y) - log.Printf("vx: %f", vx) - log.Printf("vy: %f", vy) - log.Printf("m: %f", m) - - s1 := structs.Star2D{ - C: structs.Vec2{x, y}, - V: structs.Vec2{vx, vy}, - M: m, - } - - log.Printf("s1: %v", s1) - - treeInsertError := treeArray[treeindex].Insert(s1) - if treeInsertError != nil { - panic(fmt.Sprintf("Error inserting %v into tree %d: %v", s1, treeindex, treeInsertError)) - } - - fmt.Println("-------------") - fmt.Println(treeArray) - fmt.Println("-------------") - - log.Println("Done inserting the star") - starCount[treeindex] += 1 - - pushMetricsNumOfStars("http://db:80/metrics", treeindex) - - _, _ = fmt.Fprintf(w, "%d", starCount[treeindex]) -} - -// starlistHandler lists all the stars in the given tree -func starlistHandler(w http.ResponseWriter, r *http.Request) { - log.Println("The starlist handler was accessed") - - w.Header().Set("Content-Type", "application/json") - - vars := mux.Vars(r) - treeindex, _ := strconv.ParseInt(vars["treeindex"], 10, 0) - - listofallstars := treeArray[treeindex].GetAllStars() - log.Printf("listofallstars: %v", listofallstars) - // listofallstars: [{{-42 10} {0 0} 100} {{10 10} {0 0} 100}] - - // convert the list of all stars to json - jsonlistofallstars, jsonMarshalErr := json.Marshal(listofallstars) - if jsonMarshalErr != nil { - panic(jsonMarshalErr) - } - - log.Printf("jsonlistofallstars: %v", string(jsonlistofallstars)) - - _, _ = fmt.Fprintln(w, string(jsonlistofallstars)) - log.Println("Done") -} - -// dumptreeHandler dumps the requested tree -func dumptreeHandler(w http.ResponseWriter, r *http.Request) { - log.Printf("The dumptree endpoint was accessed.\n") - - w.Header().Set("Content-Type", "application/json") - - vars := mux.Vars(r) - treeindex, _ := strconv.ParseInt(vars["treeindex"], 10, 0) - - // Convert the data to json - jsonData, jsonMarshalerError := json.Marshal(treeArray[treeindex]) - if jsonMarshalerError != nil { - panic(jsonMarshalerError) - } - - // print the jsonData to the ResponseWriter - _, printTreeErr := fmt.Fprintf(w, "%v\n", string(jsonData)) - if printTreeErr != nil { - panic(printTreeErr) - } -} diff --git a/metrics.go b/metrics.go deleted file mode 100644 index 5d04517..0000000 --- a/metrics.go +++ /dev/null @@ -1,45 +0,0 @@ -package main - -import ( - "fmt" - "log" - "net/http" - "net/url" -) - -// metricHandler prints all the metrics to the ResponseWriter -func metricHandler(w http.ResponseWriter, r *http.Request) { - var metricsString string - metricsString += fmt.Sprintf("nr_galaxies %d\n", len(treeArray)) - - for i := 0; i < len(starCount); i++ { - metricsString += fmt.Sprintf("galaxy_star_count{galaxy_nr=\"%d\"} %d\n", i, starCount[i]) - } - - for i := 0; i < len(errorCount); i++ { - metricsString += fmt.Sprintf("galaxy_error_count{galaxy_nr=\"%d\"} %d\n", i, errorCount[i]) - } - - log.Println(metricsString) - _, _ = fmt.Fprintf(w, metricsString) -} - -// pushMetricsNumOfStars pushes the amount of stars in the given galaxy with the given index to the given host -// the host is (normally) the service bundling the metrics -func pushMetricsNumOfStars(host string, treeindex int64) { - - // define a post-request and send it to the given host - requestURL := fmt.Sprintf("%s", host) - resp, err := http.PostForm(requestURL, - url.Values{ - "key": {fmt.Sprintf("db_%s{nr=\"%s\"}", "stars_num", treeindex)}, - "value": {fmt.Sprintf("%d", starCount[treeindex])}, - }, - ) - if err != nil { - fmt.Printf("Cound not make a POST request to %s", requestURL) - } - - // close the response body - defer resp.Body.Close() -} diff --git a/update.go b/update.go deleted file mode 100644 index 402a64c..0000000 --- a/update.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "log" - "net/http" - "strconv" - - "github.com/gorilla/mux" -) - -// updateCenterOfMassHandler updates the center of mass in each node in tree with the given index -func updateCenterOfMassHandler(w http.ResponseWriter, r *http.Request) { - log.Println("Updating the center of mass") - vars := mux.Vars(r) - treeindex, _ := strconv.ParseInt(vars["treeindex"], 10, 0) - - treeArray[treeindex].CalcCenterOfMass() -} - -// updateTotalMassHandler updates the total mass in each node in the tree with the given index -func updateTotalMassHandler(w http.ResponseWriter, r *http.Request) { - log.Println("Updating the total mass") - vars := mux.Vars(r) - treeindex, _ := strconv.ParseInt(vars["treeindex"], 10, 0) - - treeArray[treeindex].CalcTotalMass() -} -- cgit 1.4.1