From 5bf74cf05f65dd6f60e6d1f91967668d5d376a15 Mon Sep 17 00:00:00 2001 From: Yogev Mets Date: Sun, 9 Aug 2020 14:35:23 +0300 Subject: [PATCH] Subaccounts support and overall refactoring (#64) * SubAccountCreate Signed-off-by: yyyogev * jonboydell -> logzio Signed-off-by: yyyogev * package global createHttpRequest Signed-off-by: yyyogev * remake missing commit Signed-off-by: yyyogev * use global CreateHttpRequest Signed-off-by: yyyogev * handle null utilization settings Signed-off-by: yyyogev * logging Signed-off-by: yyyogev * adjust subaccount to match responses Signed-off-by: yyyogev * remove email and token Signed-off-by: yyyogev * remove nulls from read response Signed-off-by: yyyogev * add delete user status code 204 Signed-off-by: yyyogev * remove wrong validation Signed-off-by: yyyogev * add endpoint create 204 status code Signed-off-by: yyyogev * 200 -> statuscode ok Signed-off-by: yyyogev * remove circle CI Signed-off-by: yyyogev * jonboydell -> logzio Signed-off-by: yyyogev * remove redundant fields Signed-off-by: yyyogev * subaccounts doc Signed-off-by: yyyogev * remove workflow Signed-off-by: yyyogev * find account id link Signed-off-by: yyyogev * support tags in alerts Signed-off-by: yyyogev * test tags in alerts Signed-off-by: yyyogev * refactor endpoints http requests Signed-off-by: yyyogev * refactor get endpoint request Signed-off-by: yyyogev * refactor users requests Signed-off-by: yyyogev --- .circleci/config.yml | 43 ---------- .github/workflows/go.yml | 28 ------- LICENSE | 2 - README.md | 68 ++++++++++++---- alerts/alerts_test.go | 4 +- alerts/client_alerts.go | 11 ++- alerts/client_alerts_create.go | 27 ++----- alerts/client_alerts_delete.go | 6 +- alerts/client_alerts_get.go | 6 +- alerts/client_alerts_list.go | 6 +- alerts/client_alerts_update.go | 7 +- alerts/create_alerts_integration_test.go | 3 +- alerts/create_alerts_test.go | 31 ++++--- alerts/delete_alerts_integration_test.go | 2 +- alerts/get_alerts_integration_test.go | 2 +- alerts/testdata/fixtures/create_alert.json | 2 +- alerts/update_alerts_integration_test.go | 2 +- alerts/update_alerts_test.go | 14 ++-- endpoints/client_endpoints.go | 22 ++--- endpoints/client_endpoints_create.go | 22 ++--- endpoints/client_endpoints_delete.go | 14 ++-- endpoints/client_endpoints_get.go | 28 +------ endpoints/client_endpoints_list.go | 6 +- endpoints/client_endpoints_update.go | 19 ++--- .../endpoints_bigpanda_integration_test.go | 2 +- endpoints/endpoints_create_bigpanda_test.go | 2 +- endpoints/endpoints_create_datadog_test.go | 2 +- endpoints/endpoints_create_pagerduty_test.go | 2 +- endpoints/endpoints_create_slack_test.go | 2 +- endpoints/endpoints_create_victorops_test.go | 2 +- .../endpoints_custom_integration_test.go | 2 +- .../endpoints_datadog_integration_test.go | 2 +- .../endpoints_pagerduty_integration_test.go | 2 +- endpoints/endpoints_slack_integration_test.go | 2 +- endpoints/endpoints_test.go | 4 +- .../endpoints_victorops_integration_test.go | 2 +- .../validation_endpoints_integration_test.go | 2 +- go.mod | 2 +- scripts/cover.sh | 2 +- sub_accounts/client_sub_account.go | 81 +++++++++++++++++-- sub_accounts/client_sub_account_create.go | 64 +++++---------- sub_accounts/client_sub_account_delete.go | 6 +- sub_accounts/client_sub_account_get.go | 12 ++- .../client_sub_account_get_detailed.go | 4 +- sub_accounts/client_sub_account_list.go | 4 +- .../client_sub_account_list_detailed.go | 4 +- sub_accounts/client_sub_account_update.go | 10 +-- sub_accounts/sub_account_create_test.go | 6 +- sub_accounts/sub_account_get_test.go | 1 - sub_accounts/sub_account_test.go | 4 +- sub_accounts/sub_account_update_test.go | 4 +- .../fixtures/get_detailed_subaccount.json | 28 +++---- users/client_user.go | 2 +- users/client_user_create.go | 27 +------ users/client_user_delete.go | 9 ++- users/client_user_get.go | 30 +------ users/client_user_list.go | 6 +- users/client_user_suspend.go | 6 +- users/client_user_update.go | 8 +- users/user_create_integration_test.go | 6 +- users/user_create_test.go | 2 +- users/user_suspend_integration_test.go | 4 +- users/user_test.go | 4 +- users/user_update_integration_test.go | 4 +- users/user_update_test.go | 2 +- utils.go | 29 +++++++ 66 files changed, 373 insertions(+), 401 deletions(-) delete mode 100644 .circleci/config.yml delete mode 100644 .github/workflows/go.yml diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index 1c98b8b..0000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,43 +0,0 @@ -# Golang CircleCI 2.0 configuration file -# -# Check https://circleci.com/docs/2.0/language-go/ for more details -version: 2 -jobs: - build: - docker: - - image: circleci/golang:1.12 - working_directory: /go/src/github.com/jonboydell/logzio_client - steps: - - checkout - - run: go get golang.org/x/tools/cmd/cover - - run: go get github.com/mattn/goveralls - - run: go get -v -t ./... - - run: go test -v ./... -covermode=count -coverprofile=coverage.out - - run: goveralls -coverprofile=coverage.out -service=circle-ci -repotoken $COVERALLS_TOKEN - integration: - docker: - - image: circleci/golang:1.12 - - working_directory: /go/src/github.com/jonboydell/logzio_client - steps: - - checkout - - run: go get golang.org/x/tools/cmd/cover - - run: go get github.com/mattn/goveralls - - run: go get -v -t ./... - - run: go test -v -tags integration ./... -covermode=count -coverprofile=coverage.out - - run: goveralls -coverprofile=coverage.out -service=circle-ci -repotoken $COVERALLS_TOKEN -workflows: - version: 2 - build: - jobs: - - build - integration: - triggers: - - schedule: - cron: "0 0 * * *" - filters: - branches: - only: - - develop - jobs: - - integration \ No newline at end of file diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml deleted file mode 100644 index 151971c..0000000 --- a/.github/workflows/go.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: Go -on: [push] -jobs: - - build: - name: Build - runs-on: ubuntu-latest - steps: - - - name: Set up Go 1.12 - uses: actions/setup-go@v1 - with: - go-version: 1.12 - id: go - - - name: Check out code into the Go module directory - uses: actions/checkout@v1 - - - name: Get dependencies - run: | - go get -v -t -d ./... - if [ -f Gopkg.toml ]; then - curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh - dep ensure - fi - - - name: Build - run: go build -v . diff --git a/LICENSE b/LICENSE index 2cc7bb3..9cf1062 100644 --- a/LICENSE +++ b/LICENSE @@ -1,7 +1,5 @@ MIT License -Copyright (c) 2018 jonboydell - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights diff --git a/README.md b/README.md index f09f7d5..a20a18b 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,13 @@ # Logz.io Terraform client library -DEVELOP - [![Build Status](https://travis-ci.org/jonboydell/logzio_client.svg?branch=develop)](https://travis-ci.org/jonboydell/logzio_client) [![Coverage Status](https://coveralls.io/repos/github/jonboydell/logzio_client/badge.svg?branch=develop)](https://coveralls.io/github/jonboydell/logzio_client?branch=develop) - -MASTER - [![Build Status](https://travis-ci.org/jonboydell/logzio_client.svg?branch=master)](https://travis-ci.org/jonboydell/logzio_client) - -Client library for logz.io API, see below for supported endpoints. +Client library for Logz.io API, see below for supported endpoints. The primary purpose of this library is to act as the API interface for the logz.io Terraform provider. - -Logz.io have not written an especially consistent API. Sometimes, JSON will be presented back from an API call, sometimes not. Sometimes just a status code, sometimes a 200 status code, but with an error message in the body. I have attempted to shield the user of this library from those inconsistencies, but as they are laregely not documented, it's pretty diffcult to know if I've got them all. - -[Roadmap](#roadmap) +To use it, you'll need to [create an API token](https://app.logz.io/#/dashboard/settings/api-tokens) and provide it to the client library along with your logz.io regional [API server address](https://docs.logz.io/user-guide/accounts/account-region.html#regions-and-urls). ##### Usage -Note: the lastest version of the API (1.1) is not backwards compatible with previous versions, specifically the client entrypoint names have changed to prevent naming conflicts. Use `UsersClient` ([Users API](#users)) , `AlertsClient` ([Alerts API](#alerts)) and `EndpointsClient` ([Endpoints API](#endpoints)) rather than `Users`, `Alerts` and `Endpoints`. +Note: the lastest version of the API (1.3) is not backwards compatible with previous versions, specifically the client entrypoint names have changed to prevent naming conflicts. Use `UsersClient` ([Users API](#users)) ,`SubaccountClient` ([Sub-accounts API](#sub-accounts)), `AlertsClient` ([Alerts API](#alerts)) and `EndpointsClient` ([Endpoints API](#endpoints)) rather than `Users`, `Alerts` and `Endpoints`. ##### Alerts @@ -24,8 +17,8 @@ To create an alert where the type field = 'mytype' and the loglevel field = ERRO https://support.logz.io/hc/en-us/articles/209487329-How-do-I-create-an-Alert- ```go -client, _ := alerts.New(apiToken) -client.CreateAlert(alerts.CreateAlertType{ +client, _ := alerts.New(apiToken, apiServerAddress) +alert := client.CreateAlert(alerts.CreateAlertType{ Title: "this is my alert", Description: "this is my description", QueryString: "loglevel:ERROR", @@ -59,10 +52,10 @@ client.CreateAlert(alerts.CreateAlertType{ ##### Users -To create a new user, on a specific account or sub-account (you can get your account id from the logz.io console) +To create a new user, on a specific account or sub-account. you'll need [your account Id](https://docs.logz.io/user-guide/accounts/finding-your-account-id.html). ```go -client, _ := users.New(apiToken) +client, _ := users.New(apiToken, apiServerAddress) user := client.User{ Username: "createa@test.user", Fullname: "my username", @@ -81,11 +74,47 @@ user := client.User{ |suspend user|`func (c *UsersClient) SuspendUser(userId int32) (bool, error)`| |unsuspend user|`func (c *UsersClient) UnSuspendUser(userId int32) (bool, error)`| +##### Sub-accounts + +To create a new sub-account, on a main account. +```go +client, _ := sub_accounts.New(apiToken, apiServerAddress) +subaccount := sub_accounts.SubAccountCreate{ + Email: "test.user@email.com", + AccountName: "my account name", + MaxDailyGB: 6.5, + RetentionDays: 4, + Searchable: true, + Accessible: false, + SharingObjectAccounts: []int32{accountId1, accountId2}, //Id's of the accounts who will be able to access this account + DocSizeSetting: true, +} +``` + +|function|func name| +|---|---| +|create sub-account|`func (c *SubAccountClient) CreateSubAccount(subAccount SubAccountCreate) (*SubAccount, error) `| +|update sub-account|`func (c *SubAccountClient) UpdateSubAccount(id int64, subAccount SubAccount) error`| +|delete sub-account|`func (c *SubAccountClient) DeleteSubAccount(id int64) error`| +|get sub-account|`func (c *SubAccountClient) GetSubAccount(id int64) (*SubAccount, error)`| +|get detailed sub-account|`func (c *SubAccountClient) GetDetailedSubAccount(id int64) (*SubAccountDetailed, error)`| +|list sub-accounts|`func (c *SubAccountClient) ListSubAccounts() ([]SubAccount, error)`| +|list detailed sub-accounts|`func (c *SubAccountClient) DetailedSubAccounts() ([]SubAccountDetailed, error) `| + ##### Endpoints -There's no 1-1 mapping between this library and the logz.io API functions, logz.io provide one API endpoint per *type* of notification endpoint being created. I have abstracted this so that depending on how you create your `Endpoints` variable that you pass to `CreateEndpoint` the `CreateEndpoint` function will work out which API call to make. +For each type of endpoint there is a different structure, below you can find an example for creating a Slack endpoint. +For more info, see: https://docs.logz.io/api/#tag/Manage-notification-endpoints or check our endpoints tests for more examples. -For more info, see: https://docs.logz.io/api/#tag/Manage-notification-endpoints +```go +client, _ := endpoints.New(apiToken, apiServerAddress) +endpoint, err := underTest.CreateEndpoint(endpoints.Endpoint{ + Title: "some_endpoint", + Description: "my description", + Url: "https://this.is.com/some/webhook", + EndpointType: endpoints.EndpointTypeSlack, + }) +``` #### Contributing @@ -96,4 +125,11 @@ For more info, see: https://docs.logz.io/api/#tag/Manage-notification-endpoints `go test -v -race ./...` +### Changelog +- v1.3 + - unnecessary resource updates bug fix. + - support tags in alerts +- v1.2 + - Add subaccount support + diff --git a/alerts/alerts_test.go b/alerts/alerts_test.go index 41b42e4..cfc9e4a 100644 --- a/alerts/alerts_test.go +++ b/alerts/alerts_test.go @@ -1,8 +1,8 @@ package alerts_test import ( - "github.com/jonboydell/logzio_client/alerts" - "github.com/jonboydell/logzio_client/test_utils" + "github.com/logzio/logzio_terraform_client/alerts" + "github.com/logzio/logzio_terraform_client/test_utils" "io/ioutil" "net/http" "net/http/httptest" diff --git a/alerts/client_alerts.go b/alerts/client_alerts.go index 416e797..fb8dd14 100644 --- a/alerts/client_alerts.go +++ b/alerts/client_alerts.go @@ -3,7 +3,7 @@ package alerts import ( "fmt" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client/client" ) const ( @@ -53,6 +53,7 @@ const ( fldTitle string = "title" fldValueAggregationField string = "valueAggregationField" fldValueAggregationType string = "valueAggregationType" + fldTags string = "tags" ) type CreateAlertType struct { @@ -70,6 +71,7 @@ type CreateAlertType struct { Title string ValueAggregationField interface{} ValueAggregationType string + Tags []string } type AlertType struct { @@ -94,6 +96,7 @@ type AlertType struct { Title string ValueAggregationField interface{} ValueAggregationType string + Tags []string } type SeverityThresholdType struct { @@ -118,6 +121,7 @@ func jsonAlertToAlert(jsonAlert map[string]interface{}) AlertType { Threshold: int(jsonAlert[fldThreshold].(float64)), Title: jsonAlert[fldTitle].(string), ValueAggregationType: jsonAlert[fldValueAggregationType].(string), + Tags: []string{}, } if jsonAlert[fldGroupByAggregationFields] != nil { @@ -136,6 +140,11 @@ func jsonAlertToAlert(jsonAlert map[string]interface{}) AlertType { alert.LastTriggeredAt = jsonAlert[fldLastTriggeredAt].(interface{}) } + tags := jsonAlert[fldTags].([]interface{}) + for _, tag := range tags { + alert.Tags = append(alert.Tags, tag.(string)) + } + tiers := jsonAlert[fldSeverityThresholdTiers].([]interface{}) for x := 0; x < len(tiers); x++ { tier := tiers[x].(map[string]interface{}) diff --git a/alerts/client_alerts_create.go b/alerts/client_alerts_create.go index d63c7e9..2280e3c 100644 --- a/alerts/client_alerts_create.go +++ b/alerts/client_alerts_create.go @@ -4,16 +4,14 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" "net/http" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" ) const createAlertServiceUrl string = alertsServiceEndpoint const createAlertServiceMethod string = http.MethodPost -const createAlertMethodSuccess int = 200 +const createAlertMethodSuccess int = http.StatusOK type FieldError struct { Field string @@ -61,8 +59,8 @@ func validateCreateAlertRequest(alert CreateAlertType) error { } } - if AggregationTypeNone == alert.ValueAggregationType && (alert.ValueAggregationField != nil || alert.GroupByAggregationFields != nil) { - message := fmt.Sprintf("if ValueAggregaionType is %s then ValueAggregationField and GroupByAggregationFields must be nil", AggregationTypeNone) + if AggregationTypeNone == alert.ValueAggregationType && (alert.ValueAggregationField != nil) { + message := fmt.Sprintf("if ValueAggregaionType is %s then ValueAggregationField must be nil", AggregationTypeNone) return FieldError{"valueAggregationTypeComposite", message} } @@ -87,6 +85,7 @@ func buildCreateAlertRequest(alert CreateAlertType) map[string]interface{} { createAlert[fldTitle] = alert.Title createAlert[fldValueAggregationField] = alert.ValueAggregationField createAlert[fldValueAggregationType] = alert.ValueAggregationType + createAlert[fldTags] = alert.Tags return createAlert } @@ -112,27 +111,13 @@ func (c *AlertsClient) CreateAlert(alert CreateAlertType) (*AlertType, error) { createAlert := buildCreateAlertRequest(alert) req, _ := c.buildCreateApiRequest(c.ApiToken, createAlert) - - httpClient := client.GetHttpClient(req) - resp, err := httpClient.Do(req) + jsonResponse, err := logzio_client.CreateHttpRequest(req) if err != nil { return nil, err } - defer resp.Body.Close() - - jsonBytes, _ := ioutil.ReadAll(resp.Body) - if !logzio_client.CheckValidStatus(resp, []int{createAlertMethodSuccess}) { - return nil, fmt.Errorf("API call %s failed with status code %d, data: %s", "CreateAlert", resp.StatusCode, jsonBytes) - } - - var jsonResponse map[string]interface{} - err = json.Unmarshal(jsonBytes, &jsonResponse) retVal := jsonAlertToAlert(jsonResponse) - if err != nil { - return nil, err - } return &retVal, nil } diff --git a/alerts/client_alerts_delete.go b/alerts/client_alerts_delete.go index 6137e3c..fcfbb2f 100644 --- a/alerts/client_alerts_delete.go +++ b/alerts/client_alerts_delete.go @@ -2,8 +2,8 @@ package alerts import ( "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" "strings" @@ -11,7 +11,7 @@ import ( const deleteAlertServiceUrl string = alertsServiceEndpoint + "/%d" const deleteAlertServiceMethod string = http.MethodDelete -const deleteAlertMethodSuccess int = 200 +const deleteAlertMethodSuccess int = http.StatusOK func (c *AlertsClient) buildDeleteApiRequest(apiToken string, alertId int64) (*http.Request, error) { baseUrl := c.BaseUrl diff --git a/alerts/client_alerts_get.go b/alerts/client_alerts_get.go index e7da449..4e47c0d 100644 --- a/alerts/client_alerts_get.go +++ b/alerts/client_alerts_get.go @@ -3,8 +3,8 @@ package alerts import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" "strings" @@ -12,7 +12,7 @@ import ( const getAlertServiceUrl string = alertsServiceEndpoint + "/%d" const getAlertServiceMethod string = http.MethodGet -const getAlertMethodSuccess int = 200 +const getAlertMethodSuccess int = http.StatusOK func (c *AlertsClient) buildGetApiRequest(apiToken string, alertId int64) (*http.Request, error) { baseUrl := c.BaseUrl diff --git a/alerts/client_alerts_list.go b/alerts/client_alerts_list.go index 8c8edf0..1c14967 100644 --- a/alerts/client_alerts_list.go +++ b/alerts/client_alerts_list.go @@ -3,15 +3,15 @@ package alerts import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" ) const listAlertServiceUrl string = alertsServiceEndpoint const listAlertServiceMethod string = http.MethodGet -const listAlertMethodSuccess int = 200 +const listAlertMethodSuccess int = http.StatusOK func (c *AlertsClient) buildListApiRequest(apiToken string) (*http.Request, error) { baseUrl := c.BaseUrl diff --git a/alerts/client_alerts_update.go b/alerts/client_alerts_update.go index 489066e..7e85d3e 100644 --- a/alerts/client_alerts_update.go +++ b/alerts/client_alerts_update.go @@ -4,8 +4,8 @@ import ( "bytes" "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" "strings" @@ -13,7 +13,7 @@ import ( const updateAlertServiceUrl string = alertsServiceEndpoint + "/%d" const updateAlertServiceMethod string = http.MethodPut -const updateAlertMethodSuccess int = 200 +const updateAlertMethodSuccess int = http.StatusOK func buildUpdateAlertRequest(alert CreateAlertType) map[string]interface{} { var createAlert = map[string]interface{}{} @@ -33,6 +33,7 @@ func buildUpdateAlertRequest(alert CreateAlertType) map[string]interface{} { createAlert[fldTitle] = alert.Title createAlert[fldValueAggregationField] = alert.ValueAggregationField createAlert[fldValueAggregationType] = alert.ValueAggregationType + createAlert[fldTags] = alert.Tags return createAlert } diff --git a/alerts/create_alerts_integration_test.go b/alerts/create_alerts_integration_test.go index acefb55..e48b260 100644 --- a/alerts/create_alerts_integration_test.go +++ b/alerts/create_alerts_integration_test.go @@ -3,7 +3,7 @@ package alerts_test import ( - "github.com/jonboydell/logzio_client/alerts" + "github.com/logzio/logzio_terraform_client/alerts" "github.com/stretchr/testify/assert" "testing" "time" @@ -33,6 +33,7 @@ func TestIntegrationAlerts_CreateAlert(t *testing.T) { ValueAggregationField: nil, GroupByAggregationFields: []interface{}{"my_field"}, AlertNotificationEndpoints: []interface{}{}, + Tags: []string{"some", "words"}, }) time.Sleep(3 * time.Second) diff --git a/alerts/create_alerts_test.go b/alerts/create_alerts_test.go index 6aad8d0..3e11c4b 100644 --- a/alerts/create_alerts_test.go +++ b/alerts/create_alerts_test.go @@ -7,7 +7,7 @@ import ( "net/http" "testing" - "github.com/jonboydell/logzio_client/alerts" + "github.com/logzio/logzio_terraform_client/alerts" "github.com/stretchr/testify/assert" ) @@ -26,6 +26,8 @@ func TestAlerts_CreateAlert(t *testing.T) { assert.Contains(t, target, "description") assert.Contains(t, target, "query_string") assert.Contains(t, target, "severityThresholdTiers") + assert.Contains(t, target, "tags") + assert.Equal(t, 2, len(target["tags"].([]interface{}))) w.Header().Set("Content-Type", "application/json") fmt.Fprint(w, fixture("create_alert.json")) @@ -39,13 +41,13 @@ func TestAlerts_CreateAlert(t *testing.T) { Filter: "", Operation: alerts.OperatorGreaterThan, SeverityThresholdTiers: []alerts.SeverityThresholdType{ - alerts.SeverityThresholdType{ - alerts.SeverityHigh, - 10, + { + Severity: alerts.SeverityHigh, + Threshold: 10, }, - alerts.SeverityThresholdType{ - alerts.SeverityInfo, - 10, + { + Severity: alerts.SeverityInfo, + Threshold: 10, }, }, SearchTimeFrameMinutes: 0, @@ -56,6 +58,7 @@ func TestAlerts_CreateAlert(t *testing.T) { ValueAggregationField: nil, GroupByAggregationFields: []interface{}{"my_field"}, AlertNotificationEndpoints: []interface{}{}, + Tags: []string{"some", "words"}, } alert, err := underTest.CreateAlert(testAlert) @@ -63,6 +66,8 @@ func TestAlerts_CreateAlert(t *testing.T) { assert.Equal(t, int64(1234567), alert.AlertId) assert.Equal(t, alerts.SeverityHigh, alert.SeverityThresholdTiers[0].Severity) assert.Equal(t, alerts.SeverityInfo, alert.SeverityThresholdTiers[1].Severity) + assert.Equal(t, "some", alert.Tags[0]) + assert.Equal(t, "words", alert.Tags[1]) } } @@ -85,9 +90,9 @@ func TestAlerts_CreateAlertAPIFail(t *testing.T) { Filter: "", Operation: alerts.OperatorGreaterThan, SeverityThresholdTiers: []alerts.SeverityThresholdType{ - alerts.SeverityThresholdType{ - alerts.SeverityHigh, - 10, + { + Severity: alerts.SeverityHigh, + Threshold: 10, }, }, SearchTimeFrameMinutes: 0, @@ -112,9 +117,9 @@ func TestAlerts_CreateAlertNoTitle(t *testing.T) { Filter: "", Operation: alerts.OperatorGreaterThan, SeverityThresholdTiers: []alerts.SeverityThresholdType{ - alerts.SeverityThresholdType{ - alerts.SeverityHigh, - 10, + { + Severity: alerts.SeverityHigh, + Threshold: 10, }, }, SearchTimeFrameMinutes: 0, diff --git a/alerts/delete_alerts_integration_test.go b/alerts/delete_alerts_integration_test.go index ffa07f8..590e6d2 100644 --- a/alerts/delete_alerts_integration_test.go +++ b/alerts/delete_alerts_integration_test.go @@ -3,7 +3,7 @@ package alerts_test import ( - "github.com/jonboydell/logzio_client/alerts" + "github.com/logzio/logzio_terraform_client/alerts" "github.com/stretchr/testify/assert" "testing" "time" diff --git a/alerts/get_alerts_integration_test.go b/alerts/get_alerts_integration_test.go index f477182..9aa6c83 100644 --- a/alerts/get_alerts_integration_test.go +++ b/alerts/get_alerts_integration_test.go @@ -3,7 +3,7 @@ package alerts_test import ( - "github.com/jonboydell/logzio_client/alerts" + "github.com/logzio/logzio_terraform_client/alerts" "github.com/stretchr/testify/assert" "testing" ) diff --git a/alerts/testdata/fixtures/create_alert.json b/alerts/testdata/fixtures/create_alert.json index 9e441e2..2aaf779 100644 --- a/alerts/testdata/fixtures/create_alert.json +++ b/alerts/testdata/fixtures/create_alert.json @@ -32,5 +32,5 @@ } ], "lastTriggeredAt": null, - "tags": [] + "tags": ["some", "words"] } \ No newline at end of file diff --git a/alerts/update_alerts_integration_test.go b/alerts/update_alerts_integration_test.go index 4b716ef..d6aeb79 100644 --- a/alerts/update_alerts_integration_test.go +++ b/alerts/update_alerts_integration_test.go @@ -3,7 +3,7 @@ package alerts_test import ( - "github.com/jonboydell/logzio_client/alerts" + "github.com/logzio/logzio_terraform_client/alerts" "github.com/stretchr/testify/assert" "testing" "time" diff --git a/alerts/update_alerts_test.go b/alerts/update_alerts_test.go index 23c20c5..f72e2a0 100644 --- a/alerts/update_alerts_test.go +++ b/alerts/update_alerts_test.go @@ -3,7 +3,7 @@ package alerts_test import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client/alerts" + "github.com/logzio/logzio_terraform_client/alerts" "github.com/stretchr/testify/assert" "io/ioutil" "net/http" @@ -41,9 +41,9 @@ func TestAlerts_UpdateAlert(t *testing.T) { Filter: "", Operation: alerts.OperatorGreaterThan, SeverityThresholdTiers: []alerts.SeverityThresholdType{ - alerts.SeverityThresholdType{ - alerts.SeverityHigh, - 10, + { + Severity: alerts.SeverityHigh, + Threshold: 10, }, }, SearchTimeFrameMinutes: 0, @@ -79,9 +79,9 @@ func TestAlerts_UpdateAlert_NotExist(t *testing.T) { Filter: "", Operation: alerts.OperatorGreaterThan, SeverityThresholdTiers: []alerts.SeverityThresholdType{ - alerts.SeverityThresholdType{ - alerts.SeverityHigh, - 10, + { + Severity: alerts.SeverityHigh, + Threshold: 10, }, }, SearchTimeFrameMinutes: 0, diff --git a/endpoints/client_endpoints.go b/endpoints/client_endpoints.go index 6800ef3..a8d688c 100644 --- a/endpoints/client_endpoints.go +++ b/endpoints/client_endpoints.go @@ -3,12 +3,11 @@ package endpoints import ( "errors" "fmt" - "io/ioutil" "net/http" "strings" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" ) const ( @@ -130,29 +129,24 @@ func New(apiToken, baseUrl string) (*EndpointsClient, error) { type endpointValidator = func(e Endpoint) bool type endpointBuilder = func(a string, t endpointType, e Endpoint) (*http.Request, error) -type endpointChecker = func(b []byte) error +type endpointChecker = func(data map[string]interface{}) error -func (c *EndpointsClient) makeEndpointRequest(endpoint interface{}, validator endpointValidator, builder endpointBuilder, checker endpointChecker) ([]byte, error, bool) { +func (c *EndpointsClient) makeEndpointRequest(endpoint interface{}, validator endpointValidator, builder endpointBuilder, checker endpointChecker) (map[string]interface{}, error, bool) { e := endpoint.(Endpoint) if !validator(e) { return nil, errors.New("the passed in endpoint is not valid"), false } req, _ := builder(c.ApiToken, e.EndpointType, e) - httpClient := client.GetHttpClient(req) - resp, err := httpClient.Do(req) + jsonResponse, err := logzio_client.CreateHttpRequest(req) if err != nil { return nil, err, false } - defer resp.Body.Close() - jsonBytes, _ := ioutil.ReadAll(resp.Body) - if !logzio_client.CheckValidStatus(resp, []int{http.StatusOK}) { - return nil, fmt.Errorf(errorCreateEndpointApiCallFailed, resp.StatusCode, jsonBytes), false - } - err = checker(jsonBytes) + + err = checker(jsonResponse) if err != nil { return nil, err, false } - return jsonBytes, nil, true + return jsonResponse, err, true } func (c *EndpointsClient) getURLByType(t endpointType) string { diff --git a/endpoints/client_endpoints_create.go b/endpoints/client_endpoints_create.go index 86cba43..ccc35bb 100644 --- a/endpoints/client_endpoints_create.go +++ b/endpoints/client_endpoints_create.go @@ -7,7 +7,7 @@ import ( "net/http" "strings" - "github.com/jonboydell/logzio_client" + "github.com/logzio/logzio_terraform_client" ) const ( @@ -83,10 +83,7 @@ func (c *EndpointsClient) buildCreateEndpointApiRequest(apiToken string, endpoin // Creates an endpoint, given the endpoint definition and the service to create the endpoint against // Returns the endpoint object if successful (hopefully with an ID) and a non-nil error if not func (c *EndpointsClient) CreateEndpoint(endpoint Endpoint) (*Endpoint, error) { - if jsonBytes, err, ok := c.makeEndpointRequest(endpoint, ValidateEndpointRequest, c.buildCreateEndpointApiRequest, func(b []byte) error { - var data map[string]interface{} - json.Unmarshal(b, &data) - + if target, err, ok := c.makeEndpointRequest(endpoint, ValidateEndpointRequest, c.buildCreateEndpointApiRequest, func(data map[string]interface{}) error { if val, ok := data["errorCode"]; ok { return fmt.Errorf("%v", val) } @@ -95,19 +92,16 @@ func (c *EndpointsClient) CreateEndpoint(endpoint Endpoint) (*Endpoint, error) { return fmt.Errorf("%v", val) } - if strings.Contains(fmt.Sprintf("%s", b), errorCreateEndpointApiCallFailed) { - return fmt.Errorf(errorCreateEndpointApiCallFailed, 200, errorCreateEndpointApiCallFailed) + if strings.Contains(fmt.Sprintf("%s", data), errorCreateEndpointApiCallFailed) { + return fmt.Errorf(errorCreateEndpointApiCallFailed, http.StatusOK, errorCreateEndpointApiCallFailed) } return nil }); !ok { return nil, err } else { - var target Endpoint - err = json.Unmarshal(jsonBytes, &target) - if err != nil { - return nil, err - } - - return &target, nil + var endpoint Endpoint + jsonBytes, _ := json.Marshal(target) + json.Unmarshal(jsonBytes, &endpoint) + return &endpoint, nil } } diff --git a/endpoints/client_endpoints_delete.go b/endpoints/client_endpoints_delete.go index d97cca6..658a293 100644 --- a/endpoints/client_endpoints_delete.go +++ b/endpoints/client_endpoints_delete.go @@ -5,13 +5,13 @@ import ( "net/http" "strings" - "github.com/jonboydell/logzio_client" + "github.com/logzio/logzio_terraform_client" ) const ( deleteEndpointServiceUrl string = endpointServiceEndpoint + "/%d" deleteEndpointServiceMethod string = http.MethodDelete - deleteEndpointMethodSuccess int = 200 + deleteEndpointMethodSuccess int = http.StatusOK ) const ( @@ -31,12 +31,12 @@ func (c *EndpointsClient) buildDeleteEndpointApiRequest(apiToken string, service // Deletes an endpoint with the given id, returns a non nil error otherwise func (c *EndpointsClient) DeleteEndpoint(endpointId int64) error { - if _, err, ok := c.makeEndpointRequest(Endpoint{Id: endpointId}, validateDeleteEndpoint, c.buildDeleteEndpointApiRequest, func(body []byte) error { - if strings.Contains(fmt.Sprintf("%s", body), "endpoints/FORBIDDEN_OPERATION") { - return fmt.Errorf(errorDeleteEndpointDoesntExist, endpointId, body) + if _, err, ok := c.makeEndpointRequest(Endpoint{Id: endpointId}, validateDeleteEndpoint, c.buildDeleteEndpointApiRequest, func(data map[string]interface{}) error { + if strings.Contains(fmt.Sprintf("%s", data), "endpoints/FORBIDDEN_OPERATION") { + return fmt.Errorf(errorDeleteEndpointDoesntExist, endpointId, data) } - if strings.Contains(fmt.Sprintf("%s", body), "endpoints/UNKNOWN_ENDPOINT") { - return fmt.Errorf(errorDeleteEndpointDoesntExist, endpointId, body) + if strings.Contains(fmt.Sprintf("%s", data), "endpoints/UNKNOWN_ENDPOINT") { + return fmt.Errorf(errorDeleteEndpointDoesntExist, endpointId, data) } return nil }); !ok { diff --git a/endpoints/client_endpoints_get.go b/endpoints/client_endpoints_get.go index 45eb3d8..13d525f 100644 --- a/endpoints/client_endpoints_get.go +++ b/endpoints/client_endpoints_get.go @@ -1,18 +1,15 @@ package endpoints import ( - "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" - "io/ioutil" + "github.com/logzio/logzio_terraform_client" "net/http" "strings" ) const getEndpointsServiceUrl string = endpointServiceEndpoint + "/%d" const getEndpointsServiceMethod string = http.MethodGet -const getEndpointsMethodSuccess int = 200 +const getEndpointsMethodSuccess int = http.StatusOK const apiGetEndpointNoEndpoint = "The endpoint doesn't exist" @@ -47,33 +44,16 @@ func (c *EndpointsClient) GetEndpointByName(endpointName string) (*Endpoint, err func (c *EndpointsClient) GetEndpoint(endpointId int64) (*Endpoint, error) { req, _ := c.buildGetEnpointApiRequest(c.ApiToken, endpointId) - httpClient := client.GetHttpClient(req) - resp, err := httpClient.Do(req) + jsonEndpoint, err := logzio_client.CreateHttpRequest(req) if err != nil { return nil, err } - // @todo: this isn't the idiomatic way to read a response body - jsonBytes, _ := ioutil.ReadAll(resp.Body) - - if !logzio_client.CheckValidStatus(resp, []int{getEndpointsMethodSuccess}) { - return nil, fmt.Errorf(errorGetEndpointApiCallFailed, resp.StatusCode, jsonBytes) - } - - // sometimes logz.io returns a string rather than a json object (and a 200 status code), even though the call has failed - // @todo: can this be refactored? - str := fmt.Sprintf("%s", jsonBytes) + str := fmt.Sprintf("%s", jsonEndpoint) if strings.Contains(str, apiGetEndpointNoEndpoint) { return nil, fmt.Errorf(errorGetEndpointDoesntExist, endpointId, str) } - var jsonEndpoint map[string]interface{} - err = json.Unmarshal([]byte(jsonBytes), &jsonEndpoint) - if err != nil { - return nil, err - } - endpoint := jsonEndpointToEndpoint(jsonEndpoint) - return &endpoint, nil } diff --git a/endpoints/client_endpoints_list.go b/endpoints/client_endpoints_list.go index 61481c6..a6499b7 100644 --- a/endpoints/client_endpoints_list.go +++ b/endpoints/client_endpoints_list.go @@ -3,15 +3,15 @@ package endpoints import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" ) const listEndpointsServiceUrl string = endpointServiceEndpoint const listEndpointsServiceMethod string = http.MethodGet -const listEndpointsMethodSuccess int = 200 +const listEndpointsMethodSuccess int = http.StatusOK const errorListEndpointApiCallFailed = "API call ListEndpoints failed with status code:%d, data:%s" diff --git a/endpoints/client_endpoints_update.go b/endpoints/client_endpoints_update.go index 54ba338..613f0bf 100644 --- a/endpoints/client_endpoints_update.go +++ b/endpoints/client_endpoints_update.go @@ -7,13 +7,13 @@ import ( "net/http" "strings" - "github.com/jonboydell/logzio_client" + "github.com/logzio/logzio_terraform_client" ) const ( updateEndpointServiceUrl string = endpointServiceEndpoint + "/%s/%d" updateEndpointServiceMethod string = http.MethodPut - updateEndpointMethodSuccess int = 200 + updateEndpointMethodSuccess int = http.StatusOK ) const ( @@ -82,18 +82,19 @@ func buildUpdateEndpointRequest(endpoint Endpoint) (map[string]interface{}, erro func (c *EndpointsClient) UpdateEndpoint(id int64, endpoint Endpoint) (*Endpoint, error) { endpoint.Id = id - if jsonBytes, err, ok := c.makeEndpointRequest(endpoint, ValidateEndpointRequest, c.buildUpdateEndpointApiRequest, func(b []byte) error { - if strings.Contains(fmt.Sprintf("%s", b), "Insufficient privileges") { - return fmt.Errorf("API call %s failed for endpoint %d, data: %s", "UpdateEndpoint", id, b) + if target, err, ok := c.makeEndpointRequest(endpoint, ValidateEndpointRequest, c.buildUpdateEndpointApiRequest, func(data map[string]interface{}) error { + if strings.Contains(fmt.Sprintf("%s", data), "Insufficient privileges") { + return fmt.Errorf("API call %s failed for endpoint %d, data: %s", "UpdateEndpoint", id, data) } - if strings.Contains(fmt.Sprintf("%s", b), "errorCode") { - return fmt.Errorf("API call %s failed for endpoint %d, data: %s", "UpdateEndpoint", id, b) + if strings.Contains(fmt.Sprintf("%s", data), "errorCode") { + return fmt.Errorf("API call %s failed for endpoint %d, data: %s", "UpdateEndpoint", id, data) } return nil }); ok { - var target Endpoint - err = json.Unmarshal(jsonBytes, &target) + endpointBytes, _ := json.Marshal(target) + var endpoint Endpoint + err = json.Unmarshal(endpointBytes, &endpoint) if err != nil { return nil, err } diff --git a/endpoints/endpoints_bigpanda_integration_test.go b/endpoints/endpoints_bigpanda_integration_test.go index 1446ae2..026341b 100644 --- a/endpoints/endpoints_bigpanda_integration_test.go +++ b/endpoints/endpoints_bigpanda_integration_test.go @@ -3,7 +3,7 @@ package endpoints_test import ( - "github.com/jonboydell/logzio_client/endpoints" + "github.com/logzio/logzio_terraform_client/endpoints" "github.com/stretchr/testify/assert" "testing" ) diff --git a/endpoints/endpoints_create_bigpanda_test.go b/endpoints/endpoints_create_bigpanda_test.go index 2cba435..b11cbc1 100644 --- a/endpoints/endpoints_create_bigpanda_test.go +++ b/endpoints/endpoints_create_bigpanda_test.go @@ -7,7 +7,7 @@ import ( "net/http" "testing" - "github.com/jonboydell/logzio_client/endpoints" + "github.com/logzio/logzio_terraform_client/endpoints" "github.com/stretchr/testify/assert" ) diff --git a/endpoints/endpoints_create_datadog_test.go b/endpoints/endpoints_create_datadog_test.go index d0f74af..3389467 100644 --- a/endpoints/endpoints_create_datadog_test.go +++ b/endpoints/endpoints_create_datadog_test.go @@ -3,7 +3,7 @@ package endpoints_test import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client/endpoints" + "github.com/logzio/logzio_terraform_client/endpoints" "github.com/stretchr/testify/assert" "io/ioutil" "net/http" diff --git a/endpoints/endpoints_create_pagerduty_test.go b/endpoints/endpoints_create_pagerduty_test.go index f5f639e..c3dbc51 100644 --- a/endpoints/endpoints_create_pagerduty_test.go +++ b/endpoints/endpoints_create_pagerduty_test.go @@ -3,7 +3,7 @@ package endpoints_test import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client/endpoints" + "github.com/logzio/logzio_terraform_client/endpoints" "github.com/stretchr/testify/assert" "io/ioutil" "net/http" diff --git a/endpoints/endpoints_create_slack_test.go b/endpoints/endpoints_create_slack_test.go index 625a62b..28c39f5 100644 --- a/endpoints/endpoints_create_slack_test.go +++ b/endpoints/endpoints_create_slack_test.go @@ -3,7 +3,7 @@ package endpoints_test import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client/endpoints" + "github.com/logzio/logzio_terraform_client/endpoints" "github.com/stretchr/testify/assert" "io/ioutil" "net/http" diff --git a/endpoints/endpoints_create_victorops_test.go b/endpoints/endpoints_create_victorops_test.go index d274d34..f55ebee 100644 --- a/endpoints/endpoints_create_victorops_test.go +++ b/endpoints/endpoints_create_victorops_test.go @@ -3,7 +3,7 @@ package endpoints_test import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client/endpoints" + "github.com/logzio/logzio_terraform_client/endpoints" "github.com/stretchr/testify/assert" "io/ioutil" "net/http" diff --git a/endpoints/endpoints_custom_integration_test.go b/endpoints/endpoints_custom_integration_test.go index 127ca8e..9d55e97 100644 --- a/endpoints/endpoints_custom_integration_test.go +++ b/endpoints/endpoints_custom_integration_test.go @@ -3,7 +3,7 @@ package endpoints_test import ( - "github.com/jonboydell/logzio_client/endpoints" + "github.com/logzio/logzio_terraform_client/endpoints" "github.com/stretchr/testify/assert" "testing" ) diff --git a/endpoints/endpoints_datadog_integration_test.go b/endpoints/endpoints_datadog_integration_test.go index 13da8fa..9bafe9f 100644 --- a/endpoints/endpoints_datadog_integration_test.go +++ b/endpoints/endpoints_datadog_integration_test.go @@ -3,7 +3,7 @@ package endpoints_test import ( - "github.com/jonboydell/logzio_client/endpoints" + "github.com/logzio/logzio_terraform_client/endpoints" "github.com/stretchr/testify/assert" "testing" ) diff --git a/endpoints/endpoints_pagerduty_integration_test.go b/endpoints/endpoints_pagerduty_integration_test.go index 68050b6..fb42ccb 100644 --- a/endpoints/endpoints_pagerduty_integration_test.go +++ b/endpoints/endpoints_pagerduty_integration_test.go @@ -3,7 +3,7 @@ package endpoints_test import ( - "github.com/jonboydell/logzio_client/endpoints" + "github.com/logzio/logzio_terraform_client/endpoints" "github.com/stretchr/testify/assert" "testing" ) diff --git a/endpoints/endpoints_slack_integration_test.go b/endpoints/endpoints_slack_integration_test.go index ccf0e17..f447154 100644 --- a/endpoints/endpoints_slack_integration_test.go +++ b/endpoints/endpoints_slack_integration_test.go @@ -3,7 +3,7 @@ package endpoints_test import ( - "github.com/jonboydell/logzio_client/endpoints" + "github.com/logzio/logzio_terraform_client/endpoints" "github.com/stretchr/testify/assert" "testing" ) diff --git a/endpoints/endpoints_test.go b/endpoints/endpoints_test.go index b6f18b0..b19d871 100644 --- a/endpoints/endpoints_test.go +++ b/endpoints/endpoints_test.go @@ -1,8 +1,8 @@ package endpoints_test import ( - "github.com/jonboydell/logzio_client/endpoints" - "github.com/jonboydell/logzio_client/test_utils" + "github.com/logzio/logzio_terraform_client/endpoints" + "github.com/logzio/logzio_terraform_client/test_utils" "io/ioutil" "net/http" "net/http/httptest" diff --git a/endpoints/endpoints_victorops_integration_test.go b/endpoints/endpoints_victorops_integration_test.go index c5bca02..ae93e6a 100644 --- a/endpoints/endpoints_victorops_integration_test.go +++ b/endpoints/endpoints_victorops_integration_test.go @@ -3,7 +3,7 @@ package endpoints_test import ( - "github.com/jonboydell/logzio_client/endpoints" + "github.com/logzio/logzio_terraform_client/endpoints" "github.com/stretchr/testify/assert" "testing" ) diff --git a/endpoints/validation_endpoints_integration_test.go b/endpoints/validation_endpoints_integration_test.go index 50ac890..4f76c17 100644 --- a/endpoints/validation_endpoints_integration_test.go +++ b/endpoints/validation_endpoints_integration_test.go @@ -3,7 +3,7 @@ package endpoints_test import ( "testing" - "github.com/jonboydell/logzio_client/endpoints" + "github.com/logzio/logzio_terraform_client/endpoints" "github.com/stretchr/testify/assert" ) diff --git a/go.mod b/go.mod index 6a944ac..3a06c8c 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/jonboydell/logzio_client +module github.com/logzio/logzio_terraform_client go 1.12 diff --git a/scripts/cover.sh b/scripts/cover.sh index ca36300..f861326 100755 --- a/scripts/cover.sh +++ b/scripts/cover.sh @@ -1,4 +1,4 @@ #!/usr/bin/env bash if [ -z ${LOGZIO_API_TOKEN} ]; then echo "Must supply a LOGZIO_API_TOKEN env var" && exit 1; fi -PREFIX=github.com/jonboydell/logzio_client +PREFIX=github.com/logzio/logzio_terraform_client go test ${PREFIX}/alerts ${PREFIX}/client ${PREFIX}/endpoints ${PREFIX}/users -coverprofile=coverage.out && go tool cover -html=coverage.out \ No newline at end of file diff --git a/sub_accounts/client_sub_account.go b/sub_accounts/client_sub_account.go index 2ff2051..e0b3e01 100644 --- a/sub_accounts/client_sub_account.go +++ b/sub_accounts/client_sub_account.go @@ -1,12 +1,15 @@ package sub_accounts import ( + "encoding/json" "fmt" - "github.com/jonboydell/logzio_client/client" + "github.com/hashicorp/go-hclog" + "github.com/logzio/logzio_terraform_client/client" ) const ( subAccountServiceEndpoint = "%s/v1/account-management/time-based-accounts" + loggerName = "logzio-client" ) const ( @@ -28,7 +31,6 @@ const ( type SubAccount struct { Id int64 - Email string AccountName string MaxDailyGB float32 RetentionDays int32 @@ -37,12 +39,54 @@ type SubAccount struct { SharingObjectAccounts []interface{} DocSizeSetting bool UtilizationSettings map[string]interface{} +} + +type SubAccountRelation struct { + OwnerAccountId int64 `json:"ownerAccountId"` + SubAccountId int64 `json:"subAccountId"` + Searchable bool `json:"searchable"` + Accessible bool `json:"accessible"` + CreatedDate int64 `json:"createdDate"` + LastUpdatedDate int64 `json:"lastUpdatedDate"` + LastUpdaterUserId int64 `json:"lastUpdaterUserId"` + Type string `json:"type"` +} + +type Account struct { + AccountId int64 `json:"accountId"` + AccountToken string `json:"accountToken"` + AccountName string `json:"accountName"` + Active bool `json:"active"` + EsIndexPrefix string `json:"esIndexPrefix"` + MaxDailyGB int64 `json:"maxDailyGB"` + RetentionDays int64 `json:"retentionDays"` +} + +type SubAccountDetailed struct { + SubAccountRelation SubAccountRelation `json:"subAccountRelation"` + Account Account `json:"account"` + SharingObjectAccounts []interface{} `json:"sharingObjectsAccounts"` + UtilizationSettings map[string]interface{} `json:"utilizationSettings"` + DailyUsagesList map[string]interface{} `json:"dailyUsagesList"` + DocSizeSetting bool `json:"docSizeSetting"`} + +type SubAccountCreate struct { + Email string + AccountName string + MaxDailyGB float32 + RetentionDays int32 + Searchable bool + Accessible bool + SharingObjectAccounts []int32 + DocSizeSetting bool + UtilizationSettings map[string]interface{} AccountToken string DailyUsagesList interface{} } type SubAccountClient struct { *client.Client + logger hclog.Logger } // Creates a new entry point into the sub-account functions, accepts the user's logz.io API token and account Id @@ -56,16 +100,19 @@ func New(apiToken string, baseUrl string) (*SubAccountClient, error) { c := &SubAccountClient{ Client: client.New(apiToken, baseUrl), + logger: hclog.New(&hclog.LoggerOptions{ + Level: hclog.Debug, + Name: loggerName, + JSONFormat: true, + }), } return c, nil } func jsonToSubAccount(json map[string]interface{}) SubAccount { subAccount := SubAccount{ - Id: int64(json[fldAccountId].(float64)), - Email: json[fldEmail].(string), + Id: int64(json[fldAccountId].(float64)), AccountName: json[fldAccountName].(string), - AccountToken: json[fldAccountToken].(string), MaxDailyGB: float32(json[fldMaxDailyGB].(float64)), RetentionDays: int32(json[fldRetentionDays].(float64)), Searchable: json[fldSearchable].(bool), @@ -73,7 +120,29 @@ func jsonToSubAccount(json map[string]interface{}) SubAccount { DocSizeSetting: json[fldDocSizeSetting].(bool), SharingObjectAccounts: json[fldSharingAccountObjects].([]interface{}), UtilizationSettings: json[fldUtilizationSettings].(map[string]interface{}), - DailyUsagesList: json[fldDailyUsagesList], } + + if json[fldUtilizationSettings] != nil { + subAccount.UtilizationSettings = json[fldUtilizationSettings].(map[string]interface{}) + for key, value := range subAccount.UtilizationSettings { + if value == nil { + delete(subAccount.UtilizationSettings, key) + } + } + } return subAccount } + + +func jsonToDetailedSubAccount(jsonMap map[string]interface{}) (*SubAccountDetailed, error) { + jsonBytes, err := json.Marshal(jsonMap) + if err != nil { + return nil, err + } + + var subAccount SubAccountDetailed + if err := json.Unmarshal(jsonBytes, &subAccount); err != nil { + return nil, err + } + return &subAccount, nil +} \ No newline at end of file diff --git a/sub_accounts/client_sub_account_create.go b/sub_accounts/client_sub_account_create.go index b6511a7..5dc90d0 100644 --- a/sub_accounts/client_sub_account_create.go +++ b/sub_accounts/client_sub_account_create.go @@ -4,9 +4,7 @@ import ( "bytes" "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" - "io/ioutil" + "github.com/logzio/logzio_terraform_client" "net/http" ) @@ -16,13 +14,9 @@ const ( serviceSuccess int = http.StatusOK ) -func (c *SubAccountClient) createValidateRequest(s SubAccount) (error, bool) { - return nil, true -} - -func (c *SubAccountClient) createApiRequest(apiToken string, s SubAccount) (*http.Request, error) { +func (c *SubAccountClient) createApiRequest(apiToken string, s SubAccountCreate) (*http.Request, error) { var ( - createUser = map[string]interface{}{ + createSubAccount = map[string]interface{}{ "email": s.Email, "accountName": s.AccountName, "maxDailyGB": s.MaxDailyGB, @@ -35,7 +29,7 @@ func (c *SubAccountClient) createApiRequest(apiToken string, s SubAccount) (*htt } ) - jsonBytes, err := json.Marshal(createUser) + jsonBytes, err := json.Marshal(createSubAccount) if err != nil { return nil, err } @@ -48,45 +42,29 @@ func (c *SubAccountClient) createApiRequest(apiToken string, s SubAccount) (*htt return req, err } -func (c *SubAccountClient) createHttpRequest(req *http.Request) (map[string]interface{}, error) { - httpClient := client.GetHttpClient(req) - resp, err := httpClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - jsonBytes, err := ioutil.ReadAll(resp.Body) - if !logzio_client.CheckValidStatus(resp, []int{serviceSuccess}) { - return nil, fmt.Errorf("%d %s", resp.StatusCode, jsonBytes) - } - var target map[string]interface{} - err = json.Unmarshal(jsonBytes, &target) +func (c *SubAccountClient) CreateSubAccount(subAccount SubAccountCreate) (*SubAccount, error) { + req, _ := c.createApiRequest(c.ApiToken, subAccount) + target, err := logzio_client.CreateHttpRequest(req) if err != nil { return nil, err } - return target, nil -} - -func (c *SubAccountClient) createCheckResponse(response map[string]interface{}) error { - return nil -} -func (c *SubAccountClient) CreateSubAccount(subAccount SubAccount) (*SubAccount, error) { - if err, ok := c.createValidateRequest(subAccount); !ok { - return nil, err + var sharingAccounts []interface{} + for _, obj := range subAccount.SharingObjectAccounts { + sharingAccounts = append(sharingAccounts, obj) } - req, _ := c.createApiRequest(c.ApiToken, subAccount) - target, err := c.createHttpRequest(req) - if err != nil { - return nil, err - } + createdSubAccount := SubAccount{ + Id: int64(target["accountId"].(float64)), + MaxDailyGB: subAccount.MaxDailyGB, + AccountName: subAccount.AccountName, + UtilizationSettings: subAccount.UtilizationSettings, + DocSizeSetting: subAccount.DocSizeSetting, + Accessible: subAccount.Accessible, + Searchable: subAccount.Searchable, + RetentionDays: subAccount.RetentionDays, + SharingObjectAccounts: sharingAccounts, - err = c.createCheckResponse(target) - if err != nil { - return nil, err } - - subAccount.Id = int64(target["accountId"].(float64)) - return &subAccount, nil + return &createdSubAccount, nil } diff --git a/sub_accounts/client_sub_account_delete.go b/sub_accounts/client_sub_account_delete.go index 9f21703..b0e78cb 100644 --- a/sub_accounts/client_sub_account_delete.go +++ b/sub_accounts/client_sub_account_delete.go @@ -2,8 +2,8 @@ package sub_accounts import ( "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" ) @@ -43,7 +43,7 @@ func (c *SubAccountClient) deleteHttpRequest(req *http.Request) error { return nil } -func (c *SubAccountClient) DeleteSubAccount(id int64) (error) { +func (c *SubAccountClient) DeleteSubAccount(id int64) error { if err, ok := c.deleteValidateRequest(id); !ok { return err } diff --git a/sub_accounts/client_sub_account_get.go b/sub_accounts/client_sub_account_get.go index 64d380c..88b429d 100644 --- a/sub_accounts/client_sub_account_get.go +++ b/sub_accounts/client_sub_account_get.go @@ -3,8 +3,8 @@ package sub_accounts import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" ) @@ -66,6 +66,14 @@ func (c *SubAccountClient) GetSubAccount(id int64) (*SubAccount, error) { return nil, err } + + pretty, err := json.MarshalIndent(target,""," ") + if err != nil { + c.logger.Error("Error parsing subaccount: ", err) + } else { + c.logger.Trace("subaccount:", string(pretty)) + } + subAccount := jsonToSubAccount(target) return &subAccount, nil } diff --git a/sub_accounts/client_sub_account_get_detailed.go b/sub_accounts/client_sub_account_get_detailed.go index 0bf0a9d..8f8648f 100644 --- a/sub_accounts/client_sub_account_get_detailed.go +++ b/sub_accounts/client_sub_account_get_detailed.go @@ -3,8 +3,8 @@ package sub_accounts import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" ) diff --git a/sub_accounts/client_sub_account_list.go b/sub_accounts/client_sub_account_list.go index 5f3af8f..a6a23a7 100644 --- a/sub_accounts/client_sub_account_list.go +++ b/sub_accounts/client_sub_account_list.go @@ -3,8 +3,8 @@ package sub_accounts import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" ) diff --git a/sub_accounts/client_sub_account_list_detailed.go b/sub_accounts/client_sub_account_list_detailed.go index 19262d6..85b45c5 100644 --- a/sub_accounts/client_sub_account_list_detailed.go +++ b/sub_accounts/client_sub_account_list_detailed.go @@ -3,8 +3,8 @@ package sub_accounts import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" ) diff --git a/sub_accounts/client_sub_account_update.go b/sub_accounts/client_sub_account_update.go index ff83689..e780854 100644 --- a/sub_accounts/client_sub_account_update.go +++ b/sub_accounts/client_sub_account_update.go @@ -4,8 +4,8 @@ import ( "bytes" "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" ) @@ -22,8 +22,8 @@ func (c *SubAccountClient) updateValidateRequest(id int64) (error, bool) { func (c *SubAccountClient) updateApiRequest(apiToken string, id int64, subAccount SubAccount) (*http.Request, error) { var ( - createUser = map[string]interface{}{ - "email": subAccount.Email, + updateUser = map[string]interface{}{ + //"email": subAccount.Email, "accountName": subAccount.AccountName, "maxDailyGB": subAccount.MaxDailyGB, "retentionDays": subAccount.RetentionDays, @@ -35,7 +35,7 @@ func (c *SubAccountClient) updateApiRequest(apiToken string, id int64, subAccoun } ) - jsonBytes, err := json.Marshal(createUser) + jsonBytes, err := json.Marshal(updateUser) if err != nil { return nil, err } diff --git a/sub_accounts/sub_account_create_test.go b/sub_accounts/sub_account_create_test.go index 17f3b18..e8056b1 100644 --- a/sub_accounts/sub_account_create_test.go +++ b/sub_accounts/sub_account_create_test.go @@ -3,7 +3,7 @@ package sub_accounts_test import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client/sub_accounts" + "github.com/logzio/logzio_terraform_client/sub_accounts" "github.com/stretchr/testify/assert" "io/ioutil" "net/http" @@ -36,14 +36,14 @@ func TestSubAccount_CreateValidSubAccount(t *testing.T) { fmt.Fprint(w, fixture("create_subaccount.json")) }) - sharingAccounts := make([]interface{}, 2) + sharingAccounts := make([]int32, 2) sharingAccounts[0] = 1 sharingAccounts[1] = 2 utilizationSettings := make(map[string]interface{}, 2) utilizationSettings["a"] = "v" - s := sub_accounts.SubAccount{ + s := sub_accounts.SubAccountCreate{ Email: "test.user@test.user", AccountName: "some account name", MaxDailyGB: 10.5, diff --git a/sub_accounts/sub_account_get_test.go b/sub_accounts/sub_account_get_test.go index 1f6d6e5..c4a7a30 100644 --- a/sub_accounts/sub_account_get_test.go +++ b/sub_accounts/sub_account_get_test.go @@ -27,7 +27,6 @@ func TestSubAccount_GetValidSubAccount(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, subAccount) - assert.Equal(t, "them@mycompany.com", subAccount.Email) assert.Equal(t, "404 errors", subAccount.AccountName) assert.Equal(t, float32(100), subAccount.MaxDailyGB) assert.Equal(t, int32(5), subAccount.RetentionDays) diff --git a/sub_accounts/sub_account_test.go b/sub_accounts/sub_account_test.go index ed4d99e..d9a55bb 100644 --- a/sub_accounts/sub_account_test.go +++ b/sub_accounts/sub_account_test.go @@ -1,8 +1,8 @@ package sub_accounts_test import ( - "github.com/jonboydell/logzio_client/sub_accounts" - "github.com/jonboydell/logzio_client/test_utils" + "github.com/logzio/logzio_terraform_client/sub_accounts" + "github.com/logzio/logzio_terraform_client/test_utils" "io/ioutil" "net/http" "net/http/httptest" diff --git a/sub_accounts/sub_account_update_test.go b/sub_accounts/sub_account_update_test.go index 50fa991..bfc2db7 100644 --- a/sub_accounts/sub_account_update_test.go +++ b/sub_accounts/sub_account_update_test.go @@ -3,7 +3,7 @@ package sub_accounts_test import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client/sub_accounts" + "github.com/logzio/logzio_terraform_client/sub_accounts" "github.com/stretchr/testify/assert" "io/ioutil" "net/http" @@ -25,7 +25,6 @@ func TestSubAccount_UpdateValidSubAccount(t *testing.T) { jsonBytes, _ := ioutil.ReadAll(r.Body) var target map[string]interface{} err = json.Unmarshal(jsonBytes, &target) - assert.Contains(t, target, "email") assert.Contains(t, target, "accountName") assert.Contains(t, target, "maxDailyGB") assert.Contains(t, target, "retentionDays") @@ -48,7 +47,6 @@ func TestSubAccount_UpdateValidSubAccount(t *testing.T) { utilizationSettings["a"] = "v" s := sub_accounts.SubAccount{ - Email: "test.user@test.user", AccountName: "some account name", MaxDailyGB: 10.5, RetentionDays: 10, diff --git a/sub_accounts/testdata/fixtures/get_detailed_subaccount.json b/sub_accounts/testdata/fixtures/get_detailed_subaccount.json index d146ef8..97d1020 100644 --- a/sub_accounts/testdata/fixtures/get_detailed_subaccount.json +++ b/sub_accounts/testdata/fixtures/get_detailed_subaccount.json @@ -4,29 +4,29 @@ "subAccountId": 1234567, "searchable": true, "accessible": false, - "createdDate": "2019-07-23T11:51:23.110Z", - "lastUpdatedDate": "2019-07-23T11:51:23.110Z", + "createdDate": 1584532201, + "lastUpdatedDate": 1584532202, "lastUpdaterUserId": 33342, "type": "SUB_ACCOUNT" }, "account": { - "accountId": 0, - "accountName": "string", - "accountToken": "string", + "accountId": 12345, + "accountName": "testAccount", + "accountToken": "testToken", "active": true, - "esIndexPrefix": "string", - "maxDailyGB": 0, - "retentionDays": 0 + "esIndexPrefix": "testIndex", + "maxDailyGB": 12, + "retentionDays": 123 }, "sharingObjectsAccounts": [ { - "accountId": 0, - "accountName": "string", - "accountToken": "string", + "accountId": 12345, + "accountName": "testAccount", + "accountToken": "testToken", "active": true, - "esIndexPrefix": "string", - "maxDailyGB": 0, - "retentionDays": 0 + "esIndexPrefix": "testIndex", + "maxDailyGB": 12, + "retentionDays": 123 } ], "utilizationSettings": { diff --git a/users/client_user.go b/users/client_user.go index bc368ee..f73c888 100644 --- a/users/client_user.go +++ b/users/client_user.go @@ -2,7 +2,7 @@ package users import ( "fmt" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client/client" ) const ( diff --git a/users/client_user_create.go b/users/client_user_create.go index ec3e440..1f4eeee 100644 --- a/users/client_user_create.go +++ b/users/client_user_create.go @@ -4,16 +4,14 @@ import ( "bytes" "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" - "io/ioutil" + "github.com/logzio/logzio_terraform_client" "net/http" ) const ( CreateUserServiceUrl string = userServiceEndpoint createUserServiceMethod string = http.MethodPost - createUserServiceSuccess int = 200 + createUserServiceSuccess int = http.StatusOK ) func validateUserRequest(u User) (error, bool) { @@ -49,25 +47,6 @@ func (c *UsersClient) createUserApiRequest(apiToken string, u User) (*http.Reque return req, err } -func createUserHttpRequest(req *http.Request) (map[string]interface{}, error) { - httpClient := client.GetHttpClient(req) - resp, err := httpClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - jsonBytes, err := ioutil.ReadAll(resp.Body) - if !logzio_client.CheckValidStatus(resp, []int{createUserServiceSuccess}) { - return nil, fmt.Errorf("%d %s", resp.StatusCode, jsonBytes) - } - var target map[string]interface{} - err = json.Unmarshal(jsonBytes, &target) - if err != nil { - return nil, err - } - return target, nil -} - func checkCreateUserResponse(response map[string]interface{}) error { if _, ok := response["errorCode"]; ok { return fmt.Errorf("Error creating user; %v", response) @@ -92,7 +71,7 @@ func (c *UsersClient) CreateUser(user User) (*User, error) { } req, _ := c.createUserApiRequest(c.ApiToken, user) - target, err := createUserHttpRequest(req) + target, err := logzio_client.CreateHttpRequest(req) if err != nil { return nil, err } diff --git a/users/client_user_delete.go b/users/client_user_delete.go index d33ce51..5f3a59d 100644 --- a/users/client_user_delete.go +++ b/users/client_user_delete.go @@ -4,8 +4,8 @@ import ( "bytes" "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" ) @@ -13,8 +13,9 @@ import ( const ( deleteUserServiceUrl = userServiceEndpoint + "/%d" deleteUserServiceMethod = "DELETE" - deleteUserServiceSuccess int = 200 + ) +var deleteUserServiceSuccess = []int {http.StatusOK, http.StatusNoContent} func validateDeleteUserRequest(u User) (error, bool) { return nil, true @@ -49,7 +50,7 @@ func deleteUserHttpRequest(req *http.Request) (map[string]interface{}, error) { return nil, err } defer resp.Body.Close() - if !logzio_client.CheckValidStatus(resp, []int{deleteUserServiceSuccess}) { + if !logzio_client.CheckValidStatus(resp, deleteUserServiceSuccess) { return nil, fmt.Errorf("%d", resp.StatusCode) } jsonBytes, _ := ioutil.ReadAll(resp.Body) diff --git a/users/client_user_get.go b/users/client_user_get.go index 4f1351b..bb70119 100644 --- a/users/client_user_get.go +++ b/users/client_user_get.go @@ -1,18 +1,16 @@ package users import ( - "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" - "io/ioutil" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "net/http" ) const ( getUserServiceUrl = userServiceEndpoint + "/%d" getUserServiceMethod = http.MethodGet - getUserServiceSuccess int = 200 + getUserServiceSuccess int = http.StatusOK ) func validateGetUserRequest(u User) (error, bool) { @@ -29,26 +27,6 @@ func (c *UsersClient) getUserApiRequest(apiToken string, u User) (*http.Request, return req, err } -func getUserHttpRequest(req *http.Request) (map[string]interface{}, error) { - httpClient := client.GetHttpClient(req) - resp, err := httpClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - jsonBytes, _ := ioutil.ReadAll(resp.Body) - if !logzio_client.CheckValidStatus(resp, []int{getUserServiceSuccess}) { - return nil, fmt.Errorf("%d %s", resp.StatusCode, jsonBytes) - } - - var target map[string]interface{} - err = json.Unmarshal(jsonBytes, &target) - if err != nil { - return nil, err - } - return target, nil -} - // Returns a user given their unique ID (an integer), the user ID supplied must belong to the account that the supplied // API token belongs to, returns an error otherwise func (c *UsersClient) GetUser(id int64) (*User, error) { @@ -59,7 +37,7 @@ func (c *UsersClient) GetUser(id int64) (*User, error) { } req, _ := c.getUserApiRequest(c.ApiToken, u) - target, err := getUserHttpRequest(req) + target, err := logzio_client.CreateHttpRequest(req) if err != nil { return nil, err } diff --git a/users/client_user_list.go b/users/client_user_list.go index b560ac5..21f0e1b 100644 --- a/users/client_user_list.go +++ b/users/client_user_list.go @@ -3,8 +3,8 @@ package users import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" ) @@ -12,7 +12,7 @@ import ( const ( listUserServiceUrl = userServiceEndpoint listUserServiceMethod = "GET" - listUserServiceSuccess int = 200 + listUserServiceSuccess int = http.StatusOK ) func (c *UsersClient) listUsersApiRequest(apiToken string) (*http.Request, error) { diff --git a/users/client_user_suspend.go b/users/client_user_suspend.go index e28e83c..98c3aa3 100644 --- a/users/client_user_suspend.go +++ b/users/client_user_suspend.go @@ -2,8 +2,8 @@ package users import ( "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "net/http" ) @@ -11,7 +11,7 @@ const ( suspendUserServiceUrl string = userServiceEndpoint + "/suspend/%d" unsuspendUserServiceUrl string = userServiceEndpoint + "/unsuspend/%d" suspendUserServiceMethod string = http.MethodPost - suspendUserServiceSuccess int = 200 + suspendUserServiceSuccess int = http.StatusOK ) func validateSuspendUserRequest(userId int64) (error, bool) { diff --git a/users/client_user_update.go b/users/client_user_update.go index 3c25774..a17b333 100644 --- a/users/client_user_update.go +++ b/users/client_user_update.go @@ -4,8 +4,8 @@ import ( "bytes" "encoding/json" "fmt" - "github.com/jonboydell/logzio_client" - "github.com/jonboydell/logzio_client/client" + "github.com/logzio/logzio_terraform_client" + "github.com/logzio/logzio_terraform_client/client" "io/ioutil" "net/http" ) @@ -13,7 +13,7 @@ import ( const ( updateUserServiceUrl string = userServiceEndpoint + "/%d" updateUserServiceMethod string = http.MethodPut - updateUserServiceSuccess int = 200 + updateUserServiceSuccess int = http.StatusOK ) func validateUserUpdateRequest(u User) (error, bool) { @@ -85,7 +85,7 @@ func (c *UsersClient) UpdateUser(user User) (*User, error) { } req, _ := c.updateUserApiRequest(c.ApiToken, user) - target, err := updateUserHttpRequest(req) + target, err := logzio_client.CreateHttpRequest(req) if err != nil { return nil, err } diff --git a/users/user_create_integration_test.go b/users/user_create_integration_test.go index ebfa328..7e1c65e 100644 --- a/users/user_create_integration_test.go +++ b/users/user_create_integration_test.go @@ -3,8 +3,8 @@ package users_test import ( - "github.com/jonboydell/logzio_client/test_utils" - "github.com/jonboydell/logzio_client/users" + "github.com/logzio/logzio_terraform_client/test_utils" + "github.com/logzio/logzio_terraform_client/users" "github.com/stretchr/testify/assert" "testing" ) @@ -58,7 +58,7 @@ func TestIntegrationUsers_CreateDeleteDuplicateUser(t *testing.T) { assert.Error(t, err) } - err = underTest.DeleteUser(user.Id) + defer underTest.DeleteUser(user.Id) } } diff --git a/users/user_create_test.go b/users/user_create_test.go index 77745cc..2357924 100644 --- a/users/user_create_test.go +++ b/users/user_create_test.go @@ -3,7 +3,7 @@ package users_test import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client/users" + "github.com/logzio/logzio_terraform_client/users" "github.com/stretchr/testify/assert" "io/ioutil" "net/http" diff --git a/users/user_suspend_integration_test.go b/users/user_suspend_integration_test.go index 336befd..7aa83dc 100644 --- a/users/user_suspend_integration_test.go +++ b/users/user_suspend_integration_test.go @@ -3,8 +3,8 @@ package users_test import ( - "github.com/jonboydell/logzio_client/test_utils" - "github.com/jonboydell/logzio_client/users" + "github.com/logzio/logzio_terraform_client/test_utils" + "github.com/logzio/logzio_terraform_client/users" "github.com/stretchr/testify/assert" "testing" ) diff --git a/users/user_test.go b/users/user_test.go index c915e25..f7d3107 100644 --- a/users/user_test.go +++ b/users/user_test.go @@ -1,8 +1,8 @@ package users_test import ( - "github.com/jonboydell/logzio_client/test_utils" - "github.com/jonboydell/logzio_client/users" + "github.com/logzio/logzio_terraform_client/test_utils" + "github.com/logzio/logzio_terraform_client/users" "io/ioutil" "net/http" "net/http/httptest" diff --git a/users/user_update_integration_test.go b/users/user_update_integration_test.go index 5a660da..ea32723 100644 --- a/users/user_update_integration_test.go +++ b/users/user_update_integration_test.go @@ -3,8 +3,8 @@ package users_test import ( - "github.com/jonboydell/logzio_client/test_utils" - "github.com/jonboydell/logzio_client/users" + "github.com/logzio/logzio_terraform_client/test_utils" + "github.com/logzio/logzio_terraform_client/users" "github.com/stretchr/testify/assert" "testing" ) diff --git a/users/user_update_test.go b/users/user_update_test.go index 1ecceec..f1c3078 100644 --- a/users/user_update_test.go +++ b/users/user_update_test.go @@ -3,7 +3,7 @@ package users_test import ( "encoding/json" "fmt" - "github.com/jonboydell/logzio_client/users" + "github.com/logzio/logzio_terraform_client/users" "github.com/stretchr/testify/assert" "io/ioutil" "net/http" diff --git a/utils.go b/utils.go index 8e8fc4f..049b4f7 100644 --- a/utils.go +++ b/utils.go @@ -1,9 +1,17 @@ package logzio_client import ( + "encoding/json" + "fmt" + "github.com/logzio/logzio_terraform_client/client" + "io/ioutil" "net/http" ) +const ( + serviceSuccess int = http.StatusOK +) + func AddHttpHeaders(apiToken string, req *http.Request) { req.Header.Add("X-API-TOKEN", apiToken) req.Header.Add("Content-Type", "application/json") @@ -26,3 +34,24 @@ func CheckValidStatus(response *http.Response, status []int) bool { } return false } + +func CreateHttpRequest(req *http.Request) (map[string]interface{}, error) { + httpClient := client.GetHttpClient(req) + resp, err := httpClient.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + jsonBytes, err := ioutil.ReadAll(resp.Body) + if !CheckValidStatus(resp, []int{serviceSuccess}) { + return nil, fmt.Errorf("%d %s", resp.StatusCode, jsonBytes) + } + var target map[string]interface{} + if len(jsonBytes) > 0 { + err = json.Unmarshal(jsonBytes, &target) + if err != nil { + return nil, err + } + } + return target, nil +}