Skip to content

Commit

Permalink
feat: implement base of resource server
Browse files Browse the repository at this point in the history
  • Loading branch information
marconneves committed Nov 7, 2024
1 parent 527f486 commit 7c1506d
Show file tree
Hide file tree
Showing 14 changed files with 398 additions and 52 deletions.
20 changes: 8 additions & 12 deletions coolify/project/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@ type ProjectModel struct {
Description types.String `tfsdk:"description"`
}

type ProjectWithEnvironmentsModel struct {
Id types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Description types.String `tfsdk:"description"`
type ProjectDataSourceModel struct {
ProjectModel
Environments *[]EnvironmentModel `tfsdk:"environments"`
}

Expand All @@ -27,14 +25,18 @@ type EnvironmentModel struct {
UpdatedAt types.String `tfsdk:"updated_at"`
}

func mapProjectDataSourceModel(projectData *ProjectWithEnvironmentsModel, project *coolify_sdk.Project) {
func mapCommonProjectFields(projectData *ProjectModel, project *coolify_sdk.Project) {
projectData.Id = types.StringValue(project.UUID)
projectData.Name = types.StringValue(project.Name)
if project.Description != nil {
projectData.Description = types.StringValue(*project.Description)
} else {
projectData.Description = types.StringNull()
}
}

func mapProjectDataSourceModel(projectData *ProjectDataSourceModel, project *coolify_sdk.Project) {
mapCommonProjectFields(&projectData.ProjectModel, project)

if project.Environments != nil {
environments := make([]EnvironmentModel, len(project.Environments))
Expand All @@ -60,11 +62,5 @@ func mapProjectDataSourceModel(projectData *ProjectWithEnvironmentsModel, projec
}

func mapProjectResourceModel(projectData *ProjectModel, project *coolify_sdk.Project) {
projectData.Id = types.StringValue(project.UUID)
projectData.Name = types.StringValue(project.Name)
if project.Description != nil {
projectData.Description = types.StringValue(*project.Description)
} else {
projectData.Description = types.StringNull()
}
mapCommonProjectFields(projectData, project)
}
2 changes: 1 addition & 1 deletion coolify/project/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func readProject(ctx context.Context, client coolify_sdk.Sdk, id types.String, n
}

func (d *ProjectDataSource) ReadProjectDatasource(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var project ProjectWithEnvironmentsModel
var project ProjectDataSourceModel

resp.Diagnostics.Append(req.Config.Get(ctx, &project)...)
if resp.Diagnostics.HasError() {
Expand Down
1 change: 1 addition & 0 deletions coolify/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ func getAPIToken(token types.String, resp *provider.ConfigureResponse) string {
func (p *CoolifyProvider) Resources(ctx context.Context) []func() resource.Resource {
return []func() resource.Resource{
project.NewProjectResource,
server.NewServerResource,
}
}

Expand Down
57 changes: 57 additions & 0 deletions coolify/server/create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package server

import (
"context"
"fmt"

coolify_sdk "github.com/marconneves/coolify-sdk-go"

"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
)

func (r *ServerResource) CreateServer(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var data ServerModel

resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}

tflog.Debug(ctx, "Planned data before creation", map[string]interface{}{
"name": data.Name.ValueString(),
"ip": data.IP.ValueString(),
"description": data.Description.ValueString(),
})

createDTO := coolify_sdk.CreateServerDTO{
Name: data.Name.ValueString(),
IP: data.IP.ValueString(),
Description: data.Description.ValueString(),
IsBuildServer: false,
Port: int(data.Port.ValueInt32()),
User: data.UUID.ValueString(),
PrivateKeyUUID: data.PrivateKeyUUID.ValueString(),
}

serverID, err := r.client.Server.Create(&createDTO)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to create server, got error: %s", err))
return
}

data.UUID = types.StringValue(*serverID)
tflog.Trace(ctx, "Created a server", map[string]interface{}{"server_id": serverID})

tflog.Debug(ctx, "Data after server creation", map[string]interface{}{
"uuid": data.UUID.ValueString(),
"name": data.Name.ValueString(),
"ip": data.IP.ValueString(),
"description": data.Description.ValueString(),
})

resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)

tflog.Debug(ctx, "Server state saved to file after creation")
}
26 changes: 26 additions & 0 deletions coolify/server/delete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package server

import (
"context"
"fmt"

"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-log/tflog"
)

func (r *ServerResource) DeleteServer(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var data ServerModel

resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}

err := r.client.Server.Delete(data.UUID.ValueString())
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to delete server, got error: %s", err))
return
}

tflog.Trace(ctx, "Deleted server", map[string]interface{}{"server_id": data.UUID.ValueString()})
}
45 changes: 35 additions & 10 deletions coolify/server/model.go
Original file line number Diff line number Diff line change
@@ -1,28 +1,34 @@
package server

import (
"fmt"
"strconv"
"time"

"github.com/hashicorp/terraform-plugin-framework/types"
coolify_sdk "github.com/marconneves/coolify-sdk-go"
)

type ServerModel struct {
UUID types.String `tfsdk:"uuid"`
Name types.String `tfsdk:"name"`
IP types.String `tfsdk:"ip"`
Description types.String `tfsdk:"description"`
UUID types.String `tfsdk:"uuid"`
Name types.String `tfsdk:"name"`
Description types.String `tfsdk:"description"`
IP types.String `tfsdk:"ip"`
Port types.Int32 `tfsdk:"port"`
User types.String `tfsdk:"user"`
PrivateKeyUUID types.String `tfsdk:"private_key_uuid"`
}

type ServerDataSourceModel struct {
ServerModel
HighDiskUsageNotificationSent types.Bool `tfsdk:"high_disk_usage_notification_sent"`
LogDrainNotificationSent types.Bool `tfsdk:"log_drain_notification_sent"`
Port types.String `tfsdk:"port"`
PrivateKeyID types.Int64 `tfsdk:"private_key_id"`
Proxy *ProxyModel `tfsdk:"proxy"`
Settings *SettingsModel `tfsdk:"settings"`
SwarmCluster types.String `tfsdk:"swarm_cluster"`
TeamID types.Int64 `tfsdk:"team_id"`
UnreachableCount types.Int64 `tfsdk:"unreachable_count"`
UnreachableNotificationSent types.Bool `tfsdk:"unreachable_notification_sent"`
User types.String `tfsdk:"user"`
ValidationLogs types.String `tfsdk:"validation_logs"`
CreatedAt types.String `tfsdk:"created_at"`
UpdatedAt types.String `tfsdk:"updated_at"`
Expand Down Expand Up @@ -75,7 +81,7 @@ type SettingsModel struct {
UpdatedAt types.String `tfsdk:"updated_at"`
}

func mapServerModel(data *ServerModel, server *coolify_sdk.Server) {
func mapCommonServerFields(data *ServerModel, server *coolify_sdk.Server) {
data.UUID = types.StringValue(server.UUID)
data.IP = types.StringValue(server.IP)
data.Name = types.StringValue(server.Name)
Expand All @@ -84,10 +90,25 @@ func mapServerModel(data *ServerModel, server *coolify_sdk.Server) {
data.Description = types.StringValue(*server.Description)
}

portInt64, err := strconv.ParseInt(server.Port, 10, 32)
if err != nil {
fmt.Println("Erro na conversão:", err)
return
}

port := int32(portInt64)

data.Port = types.Int32Value(port)
}

func mapServerDataSourceModel(data *ServerDataSourceModel, server *coolify_sdk.Server) {
mapCommonServerFields(&data.ServerModel, server)

// TODO: Get private key uuid founding in api
data.PrivateKeyUUID = types.StringValue(server.UUID)

data.HighDiskUsageNotificationSent = types.BoolValue(server.HighDiskUsageNotificationSent)
data.LogDrainNotificationSent = types.BoolValue(server.LogDrainNotificationSent)
data.Port = types.StringValue(server.Port)
data.PrivateKeyID = types.Int64Value(int64(server.PrivateKeyID))

if server.Proxy != nil {
proxy := ProxyModel{}
Expand Down Expand Up @@ -186,3 +207,7 @@ func mapServerModel(data *ServerModel, server *coolify_sdk.Server) {
data.CreatedAt = types.StringValue(server.CreatedAt.Format(time.RFC3339))
data.UpdatedAt = types.StringValue(server.UpdatedAt.Format(time.RFC3339))
}

func mapServerResourceModel(projectData *ServerModel, project *coolify_sdk.Server) {
mapCommonServerFields(projectData, project)
}
54 changes: 54 additions & 0 deletions coolify/server/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ import (
"context"
"fmt"

"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
coolify_sdk "github.com/marconneves/coolify-sdk-go"
)

Expand Down Expand Up @@ -36,3 +39,54 @@ func readServer(ctx context.Context, client coolify_sdk.Sdk, id types.String, na

return server, diags
}

func (s *ServerDataSource) ReadServerDataSource(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var server ServerDataSourceModel

diags := req.Config.Get(ctx, &server)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}

serverSaved, diags := readServer(ctx, *s.client, server.UUID, server.Name)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}

mapServerDataSourceModel(&server, serverSaved)

tflog.Trace(ctx, "Successfully read team data", map[string]interface{}{
"server_uuid": serverSaved.UUID,
"name": serverSaved.Name,
})

resp.Diagnostics.Append(resp.State.Set(ctx, &server)...)

}

func (r *ServerResource) ReadServerResource(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var server ServerModel

diags := req.State.Get(ctx, &server)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}

serverSaved, diags := readServer(ctx, *r.client, server.UUID, server.Name)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}

mapServerResourceModel(&server, serverSaved)

tflog.Trace(ctx, "Successfully read server data", map[string]interface{}{
"server_uuid": serverSaved.UUID,
"name": serverSaved.Name,
})

resp.Diagnostics.Append(resp.State.Set(ctx, &server)...)
}
29 changes: 3 additions & 26 deletions coolify/server/server_data_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (

"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
coolify_sdk "github.com/marconneves/coolify-sdk-go"
configure "github.com/marconneves/terraform-provider-coolify/shared"
)
Expand Down Expand Up @@ -51,11 +50,11 @@ func (s *ServerDataSource) Schema(_ context.Context, _ datasource.SchemaRequest,
Computed: true,
Description: "Indicates if a log drain notification has been sent.",
},
"port": schema.StringAttribute{
"port": schema.Int32Attribute{
Computed: true,
Description: "The port used by the server.",
},
"private_key_id": schema.Int64Attribute{
"private_key_uuid": schema.StringAttribute{
Computed: true,
Description: "The ID of the private key associated with the server.",
},
Expand Down Expand Up @@ -276,27 +275,5 @@ func (s *ServerDataSource) Configure(ctx context.Context, req datasource.Configu
}

func (s *ServerDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var server ServerModel

diags := req.Config.Get(ctx, &server)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}

serverSaved, diags := readServer(ctx, *s.client, server.UUID, server.Name)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}

mapServerModel(&server, serverSaved)

tflog.Trace(ctx, "Successfully read team data", map[string]interface{}{
"server_uuid": serverSaved.UUID,
"name": serverSaved.Name,
})

resp.Diagnostics.Append(resp.State.Set(ctx, &server)...)

s.ReadServerDataSource(ctx, req, resp)
}
4 changes: 2 additions & 2 deletions coolify/server/server_data_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func TestAccServerDataSource(t *testing.T) {
ProtoV6ProviderFactories: tests.ProviderFactories,
Steps: []resource.TestStep{
{
Config: testAccServerDataSourceConfig(`uuid = "tks4gcsgwowws8gswggkw8gs"`),
Config: testAccServerDataSourceConfig(`uuid = "kk4wskwk0k0sssc8ckcss44c"`),
Check: testAccServerDataSourceCheck(),
},
{
Expand All @@ -35,7 +35,7 @@ data "coolify_server" "test" {

func testAccServerDataSourceCheck() resource.TestCheckFunc {
return resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("data.coolify_server.test", "uuid", "tks4gcsgwowws8gswggkw8gs"),
resource.TestCheckResourceAttr("data.coolify_server.test", "uuid", "kk4wskwk0k0sssc8ckcss44c"),
resource.TestCheckResourceAttr("data.coolify_server.test", "name", "example-server"),
resource.TestCheckResourceAttr("data.coolify_server.test", "ip", "localhost"),
resource.TestCheckResourceAttr("data.coolify_server.test", "high_disk_usage_notification_sent", "false"),
Expand Down
Loading

0 comments on commit 7c1506d

Please sign in to comment.