Skip to content

Commit

Permalink
Add resource Dashboard from Json (#48)
Browse files Browse the repository at this point in the history
* Add resource Dashboard from Json

* Remove height factor changes from this PR. There is an another PR already created for this change.

* Update version to 2.1.0
  • Loading branch information
arunselvarajdb authored and louism517 committed Jun 27, 2019
1 parent 6220ef5 commit 7218446
Show file tree
Hide file tree
Showing 8 changed files with 723 additions and 9 deletions.
2 changes: 1 addition & 1 deletion version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
v2.0.0
v2.1.0
129 changes: 129 additions & 0 deletions wavefront/import_dashboard_json_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package wavefront_plugin

import (
"fmt"
"github.com/hashicorp/terraform/helper/resource"
"github.com/spaceapegames/go-wavefront"
"testing"
)

func TestAccDashboardJson_importBasic(t *testing.T) {
resourceName := "wavefront_dashboard_json.json_foobar"
var record wavefront.Dashboard

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckWavefrontDashboardJsonDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckWavefrontDashboardJsonImporter_basic(),
Check: resource.ComposeTestCheckFunc(
testAccCheckWavefrontDashboardJsonExists("wavefront_dashboard_json.json_foobar", &record),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func testAccCheckWavefrontDashboardJsonImporter_basic() string {
return fmt.Sprintf(`
resource "wavefront_dashboard_json" "json_foobar" {
dashboard_json = <<EOF
{
"name": "Terraform Test Dashboard Json",
"description": "a",
"eventFilterType": "BYCHART",
"eventQuery": "",
"defaultTimeWindow": "",
"url": "tftestimport",
"displayDescription": false,
"displaySectionTableOfContents": true,
"displayQueryParameters": false,
"sections": [
{
"name": "section 1",
"rows": [
{
"charts": [
{
"name": "chart 1",
"sources": [
{
"name": "source 1",
"query": "ts()",
"scatterPlotSource": "Y",
"querybuilderEnabled": false,
"sourceDescription": ""
}
],
"units": "someunit",
"base": 0,
"noDefaultEvents": false,
"interpolatePoints": false,
"includeObsoleteMetrics": false,
"description": "This is chart 1, showing something",
"chartSettings": {
"type": "markdown-widget",
"max": 100,
"expectedDataSpacing": 120,
"windowing": "full",
"windowSize": 10,
"autoColumnTags": false,
"columnTags": "deprecated",
"tagMode": "all",
"numTags": 2,
"customTags": [
"tag1",
"tag2"
],
"groupBySource": true,
"y1Max": 100,
"y1Units": "units",
"y0ScaleSIBy1024": true,
"y1ScaleSIBy1024": true,
"y0UnitAutoscaling": true,
"y1UnitAutoscaling": true,
"fixedLegendEnabled": true,
"fixedLegendUseRawStats": true,
"fixedLegendPosition": "RIGHT",
"fixedLegendDisplayStats": [
"stat1",
"stat2"
],
"fixedLegendFilterSort": "TOP",
"fixedLegendFilterLimit": 1,
"fixedLegendFilterField": "CURRENT",
"plainMarkdownContent": "markdown content"
},
"summarization": "MEAN"
}
],
"heightFactor": 50
}
]
}
],
"parameterDetails": {
"param": {
"hideFromView": false,
"parameterType": "SIMPLE",
"label": "test",
"defaultValue": "Label",
"valuesToReadableStrings": {
"Label": "test"
},
"selectedLabel": "Label",
"value": "test"
}
}
}
EOF
}
`)
}
7 changes: 4 additions & 3 deletions wavefront/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ func Provider() terraform.ResourceProvider {
},
},
ResourcesMap: map[string]*schema.Resource{
"wavefront_alert": resourceAlert(),
"wavefront_dashboard": resourceDashboard(),
"wavefront_alert_target": resourceTarget(),
"wavefront_alert": resourceAlert(),
"wavefront_dashboard": resourceDashboard(),
"wavefront_dashboard_json": resourceDashboardJson(),
"wavefront_alert_target": resourceTarget(),
},
ConfigureFunc: providerConfigure,
}
Expand Down
4 changes: 2 additions & 2 deletions wavefront/resource_alert.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ func resourceAlertCreate(d *schema.ResourceData, m interface{}) error {
Minutes: d.Get("minutes").(int),
ResolveAfterMinutes: d.Get("resolve_after_minutes").(int),
NotificationResendFrequencyMinutes: d.Get("notification_resend_frequency_minutes").(int),
Severity: d.Get("severity").(string),
Tags: tags,
Severity: d.Get("severity").(string),
Tags: tags,
}

// Create the alert on Wavefront
Expand Down
156 changes: 156 additions & 0 deletions wavefront/resource_dashboad_json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
package wavefront_plugin

import (
"fmt"
"github.com/hashicorp/terraform/helper/schema"
"github.com/spaceapegames/go-wavefront"
"log"
"strings"
)

func resourceDashboardJson() *schema.Resource {
return &schema.Resource{
Create: resourceDashboardJsonCreate,
Read: resourceDashboardJsonRead,
Update: resourceDashboardJsonUpdate,
Delete: resourceDashboardJsonDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"dashboard_json": {
Type: schema.TypeString,
Required: true,
ValidateFunc: ValidateDashboardJson,
StateFunc: NormalizeDashboardJson,
},
},
}

}

func buildDashboardJson(d *schema.ResourceData) (*wavefront.Dashboard, error) {
var dashboard wavefront.Dashboard
dashboardJsonString := d.Get("dashboard_json").(string)
// json is already validated during resource Validation
_ = dashboard.UnmarshalJSON([]byte(dashboardJsonString))

// set url name as the resource ID
dashboard.ID = dashboard.Url
return &dashboard, nil
}

func resourceDashboardJsonRead(d *schema.ResourceData, m interface{}) error {
dashboards := m.(*wavefrontClient).client.Dashboards()
dash := wavefront.Dashboard{
ID: d.Id(),
}
err := dashboards.Get(&dash)
if err != nil {
if strings.Contains(err.Error(), "404") {
d.SetId("")
} else {
return fmt.Errorf("error finding Wavefront Dashboard %s. %s", d.Id(), err)
}
}
bytes, err := dash.MarshalJSON()
// Use the Wavefront url as the Terraform ID
d.SetId(dash.ID)
err = d.Set("dashboard_json", NormalizeDashboardJson(string(bytes)))
if err != nil {
return fmt.Errorf("failed to set dashboard json %s. %s", d.Id(), err)
}
return nil
}

func resourceDashboardJsonCreate(d *schema.ResourceData, m interface{}) error {
log.Printf("[INFO] Create Wavefront Dashboard %s", d.Id())
dashboards := m.(*wavefrontClient).client.Dashboards()
dashboard, err := buildDashboardJson(d)

if err != nil {
return fmt.Errorf("failed to parse dashboard, %s", err)
}

err = dashboards.Create(dashboard)
if err != nil {
return fmt.Errorf("failed to create dashboard, %s", err)
}
d.SetId(dashboard.ID)
log.Printf("[INFO] Wavefront Dashboard %s Created", d.Id())
return resourceDashboardJsonRead(d, m)
}

func resourceDashboardJsonUpdate(d *schema.ResourceData, m interface{}) error {
log.Printf("[INFO] Update Wavefront Dashboard %s", d.Id())
dashboards := m.(*wavefrontClient).client.Dashboards()
dashboard, err := buildDashboardJson(d)

if err != nil {
return fmt.Errorf("failed to parse dashboard, %s", err)
}

err = dashboards.Update(dashboard)
if err != nil {
return fmt.Errorf("failed to create dashboard, %s", err)
}

log.Printf("[INFO] Wavefront Dashboard %s Updated", d.Id())
return resourceDashboardJsonRead(d, m)
}

func resourceDashboardJsonDelete(d *schema.ResourceData, m interface{}) error {
dashboards := m.(*wavefrontClient).client.Dashboards()
dash := wavefront.Dashboard{
ID: d.Id(),
}

err := dashboards.Get(&dash)
if err != nil {
return fmt.Errorf("error finding Wavefront Dashboard %s. %s", d.Id(), err)
}

// Delete the Dashboard
err = dashboards.Delete(&dash)
if err != nil {
return fmt.Errorf("failed to delete Dashboard %s. %s", d.Id(), err)
}
d.SetId("")
return nil
}

func ValidateDashboardJson(val interface{}, key string) ([]string, []error) {
dashboardJsonString := val.(string)
var dashboard wavefront.Dashboard
err := dashboard.UnmarshalJSON([]byte(dashboardJsonString))
if err != nil {
return nil, []error{err}
}
return nil, nil
}

func NormalizeDashboardJson(val interface{}) string {
dashboardJsonString := val.(string)
var dashboard wavefront.Dashboard
_ = dashboard.UnmarshalJSON([]byte(dashboardJsonString))

// set url name as the resource ID
dashboard.ID = dashboard.Url

// remove keys which are not needed for diff
dashboard.CreatedEpochMillis = 0
dashboard.UpdatedEpochMillis = 0
dashboard.CreatorId = ""
dashboard.UpdaterId = ""
dashboard.Customer = ""
dashboard.ViewsLastDay = 0
dashboard.ViewsLastWeek = 0
dashboard.ViewsLastMonth = 0
dashboard.NumCharts = 0
dashboard.NumFavorites = 0
dashboard.Favorite = false

ret, _ := dashboard.MarshalJSON()
return string(ret)
}
4 changes: 2 additions & 2 deletions wavefront/resource_dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -1001,7 +1001,7 @@ func resourceDashboardCreate(d *schema.ResourceData, m interface{}) error {
}
d.SetId(dashboard.ID)

return nil
return resourceDashboardRead(d, m)
}

type Params []map[string]interface{}
Expand Down Expand Up @@ -1070,7 +1070,7 @@ func resourceDashboardUpdate(d *schema.ResourceData, m interface{}) error {
if err != nil {
return fmt.Errorf("error Updating Dashboard %s. %s", d.Get("name"), err)
}
return nil
return resourceDashboardRead(d, m)
}

func resourceDashboardDelete(d *schema.ResourceData, m interface{}) error {
Expand Down
Loading

0 comments on commit 7218446

Please sign in to comment.