Skip to content

Commit

Permalink
integrate nomad service creation in service endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
dbrrt committed Nov 11, 2024
1 parent 6b0a212 commit d79d6cf
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 38 deletions.
36 changes: 23 additions & 13 deletions nomad/nomad.go
Original file line number Diff line number Diff line change
@@ -1,32 +1,36 @@
package nomad

import (
"dbrrt/noaas/readuri"
"fmt"
"log"
"time"

"github.com/google/uuid"
"github.com/hashicorp/nomad/api"
)

func createAJobAndGetUri() {
func CreateAJobAndGetUri(jobNameParam string, uriParam string, script bool) (string, error) {
// Create a new Nomad client
client, err := api.NewClient(api.DefaultConfig())
if err != nil {
log.Fatalf("Failed to create Nomad client: %v", err)
return "", fmt.Errorf("failed to create Nomad client: %v", err)
}

// Create and register the job
job := createServiceJob()
job, err := createServiceJob(jobNameParam, uriParam, script)
if err != nil {
return "", fmt.Errorf("error during service job creation: %v", err)
}

allocID, err := registerJobAndGetAllocationID(client, job)
if err != nil {
log.Fatalf("Failed to get allocation ID: %v", err)
return "", fmt.Errorf("failed to register job / retrieve allocation ID: %v", err)
}

// Get allocation info using the allocation ID
allocation, _, err := client.Allocations().Info(allocID, nil)
if err != nil {
log.Fatalf("Failed to retrieve allocation info: %v", err)
return "", fmt.Errorf("failed to retrieve allocation info: %v", err)
}

// Find the URI for the "www" dynamic port
Expand All @@ -53,9 +57,9 @@ func createAJobAndGetUri() {
}

if uri == "" {
fmt.Println("No URI found for the 'www' port.")
return "", fmt.Errorf("no URI found for service www")
} else {
fmt.Printf("Service available at URI: %s\n", uri)
return uri, nil
}
}

Expand Down Expand Up @@ -94,11 +98,11 @@ func registerJobAndGetAllocationID(client *api.Client, job *api.Job) (string, er
return allocID, nil
}

func createServiceJob() *api.Job {
func createServiceJob(jobName string, uri string, script bool) (*api.Job, error) {
// Define the service job
job := &api.Job{
ID: stringPtr(uuid.New().String()),
Name: stringPtr("noaas-agent"),
Name: stringPtr(jobName),
Type: stringPtr("service"),
Datacenters: []string{"*"}, // Specifies that this job can run in any datacenter
Meta: map[string]string{
Expand Down Expand Up @@ -127,6 +131,12 @@ func createServiceJob() *api.Job {
PortLabel: "www", // Use the dynamic port label for the service
}

payloadRemote, err := readuri.ReadRemoteUriPayload(uri, script)

if err != nil {
return nil, fmt.Errorf("error during remote read payload")
}

// Define task
task := &api.Task{
Name: "web",
Expand All @@ -139,12 +149,12 @@ func createServiceJob() *api.Job {
},
Templates: []*api.Template{
{
EmbeddedTmpl: stringPtr(`<h1>Hello, Nomad!</h1>`),
EmbeddedTmpl: stringPtr(payloadRemote),
DestPath: stringPtr("local/index.html"), // Render template to the index.html file
},
},
Resources: &api.Resources{
CPU: intToPtr(50), // CPU allocation
CPU: intToPtr(50), // CPU allocation in Mhz
MemoryMB: intToPtr(64), // Memory allocation
},
}
Expand All @@ -157,5 +167,5 @@ func createServiceJob() *api.Job {
// Add the task group to the job
job.TaskGroups = []*api.TaskGroup{taskGroup}

return job
return job, nil
}
2 changes: 1 addition & 1 deletion readuri/readuri.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
// Default execCommand function
var execCommand = exec.Command

func readRemoteUriPayload(uri string, script bool) (string, error) {
func ReadRemoteUriPayload(uri string, script bool) (string, error) {
resp, err := http.Get(uri)
if err != nil {
return "", fmt.Errorf("error fetching URL: %v", err)
Expand Down
16 changes: 8 additions & 8 deletions readuri/readuri_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func TestReadRemoteUriPayload(t *testing.T) {
defer ts.Close()

// Call the function with the test server's URL
result, err := readRemoteUriPayload(ts.URL, false)
result, err := ReadRemoteUriPayload(ts.URL, false)
assert.NoError(t, err)
assert.Equal(t, "Hello, World!", result)
})
Expand All @@ -32,15 +32,15 @@ func TestReadRemoteUriPayload(t *testing.T) {
defer ts.Close()

// Call the function
result, err := readRemoteUriPayload(ts.URL, false)
result, err := ReadRemoteUriPayload(ts.URL, false)
assert.Error(t, err)
assert.Contains(t, err.Error(), "failed to retrieve content. Status code: 404")
assert.Empty(t, result)
})

t.Run("Test HTTP request failure", func(t *testing.T) {
// Using an invalid URL to simulate failure
result, err := readRemoteUriPayload("http://invalid-url", false)
result, err := ReadRemoteUriPayload("http://invalid-url", false)
assert.Error(t, err)
assert.Contains(t, err.Error(), "error fetching URL:")
assert.Empty(t, result)
Expand All @@ -53,7 +53,7 @@ func TestReadRemoteUriPayload(t *testing.T) {
}))
defer ts.Close()

result, err := readRemoteUriPayload(ts.URL, false)
result, err := ReadRemoteUriPayload(ts.URL, false)
assert.Error(t, err)
assert.Empty(t, result)
})
Expand All @@ -74,7 +74,7 @@ func TestReadRemoteUriPayload(t *testing.T) {
}

// Test the function with script flag set to true
result, err := readRemoteUriPayload(ts.URL, true)
result, err := ReadRemoteUriPayload(ts.URL, true)
assert.NoError(t, err)
assert.Equal(t, "Hello from the script\n", result)
})
Expand All @@ -94,7 +94,7 @@ func TestReadRemoteUriPayload(t *testing.T) {
return exec.Command("sh", "-c", "invalid script")
}

result, err := readRemoteUriPayload(ts.URL, true)
result, err := ReadRemoteUriPayload(ts.URL, true)
assert.Error(t, err)
assert.Contains(t, err.Error(), "error executing script:")
assert.Empty(t, result)
Expand All @@ -108,14 +108,14 @@ func TestReadRemoteUriPayload(t *testing.T) {
defer ts.Close()

// Call the function
result, err := readRemoteUriPayload(ts.URL, false)
result, err := ReadRemoteUriPayload(ts.URL, false)
assert.NoError(t, err)
assert.Empty(t, result)
})

t.Run("Test invalid URI", func(t *testing.T) {
// Test invalid URI
result, err := readRemoteUriPayload("http://", false)
result, err := ReadRemoteUriPayload("http://", false)
assert.Error(t, err)
assert.Contains(t, err.Error(), "error fetching URL:")
assert.Empty(t, result)
Expand Down
33 changes: 17 additions & 16 deletions routing/service.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package routing

import (
"dbrrt/noaas/nomad"
"fmt"
"net/http"
"net/url"

Expand All @@ -12,7 +14,7 @@ type ServiceController struct{}

type NewServiceRequest struct {
Url string `json:"url" binding:"required,url"`
Script bool `json:"script" binding:"required"`
Script bool `json:"script"`
}

type NewServiceResponseStruct struct {
Expand Down Expand Up @@ -41,21 +43,20 @@ func (h ServiceController) ServiceProvisionner(c *gin.Context) {
})

} else {

// nameParam := c.Params.ByName("name")

// if nameParam == "" {
// c.JSON(http.StatusBadRequest, gin.H{
// "url": nil,
// "error": fmt.Errorf("Missing name parameter"),
// })
// }

c.JSON(http.StatusOK, gin.H{
"url": "<DEPLOYED_URI>", // Deployed URL
"error": nil,
})

nameParam := c.Params.ByName("name")
uriDeployed, err := nomad.CreateAJobAndGetUri(nameParam, payload.Url, payload.Script)

if uriDeployed != "" && err == nil {
c.JSON(http.StatusOK, gin.H{
"url": fmt.Sprintf("http://%s", uriDeployed),
"error": nil,
})
} else {
c.JSON(http.StatusOK, gin.H{
"url": nil,
"error": fmt.Errorf("something wrong happened during job creation"),
})
}
}

}

0 comments on commit d79d6cf

Please sign in to comment.