GithubHelp home page GithubHelp logo

civo / civogo Goto Github PK

View Code? Open in Web Editor NEW
33.0 12.0 20.0 665 KB

Golang client to interact with Civo's API

Home Page: https://www.civo.com/

License: MIT License

Go 100.00%
civo-api cloud golang-client golang golang-library

civogo's Introduction

Civogo - The Golang client library for Civo

go.dev reference Build Status Lint

Civogo is a Go client library for accessing the Civo cloud API.

You can view the client API docs at https://pkg.go.dev/github.com/civo/civogo and view the API documentation at https://api.civo.com

Install

go get github.com/civo/civogo

Usage

import "github.com/civo/civogo"

From there you create a Civo client specifying your API key and a region. Then you can use public methods to interact with Civo's API.

Authentication

You will need both an API key and a region code to create a new client.

Your API key is listed within the Civo control panel's security page. You can also reset the token there, for example, if accidentally put it in source code and found it had been leaked.

For the region code, use any region you know exists, e.g. LON1. See the API documentation for details.

package main

import (
	"context"
	"github.com/civo/civogo"
)

const (
    apiKey = "mykeygoeshere"
    regionCode = "LON1"
)

func main() {
  client, err := civogo.NewClient(apiKey, regionCode)
  // ...
}

Examples

To create a new Instance:

config, err := client.NewInstanceConfig()
if err != nil {
  t.Errorf("Failed to create a new config: %s", err)
  return err
}

config.Hostname = "foo.example.com"

instance, err := client.CreateInstance(config)
if err != nil {
  t.Errorf("Failed to create instance: %s", err)
  return err
}

To get all Instances:

instances, err := client.ListAllInstances()
if err != nil {
  t.Errorf("Failed to create instance: %s", err)
  return err
}

for _, i := range instances {
    fmt.Println(i.Hostname)
}

Pagination

If a list of objects is paginated by the API, you must request pages individually. For example, to fetch all instances without using the ListAllInstances method:

func MyListAllInstances(client *civogo.Client) ([]civogo.Instance, error) {
    list := []civogo.Instance{}

    pageOfItems, err := client.ListInstances(1, 50)
    if err != nil {
        return []civogo.Instance{}, err
    }

    if pageOfItems.Pages == 1 {
        return pageOfItems.Items, nil
    }

    for page := 2;  page<=pageOfItems.Pages; page++ {
        pageOfItems, err := client.ListInstances(1, 50)
        if err != nil {
            return []civogo.Instance{}, err
        }

        list = append(list, pageOfItems.Items)
    }

    return list, nil
}

Error handler

​ In the latest version of the library we have added a new way to handle errors. Below are some examples of how to use the new error handler, and the complete list of errors is here. ​ This is an example of how to make use of the new errors, suppose we want to create a new Kubernetes cluster, and do it this way but choose a name that already exists within the clusters that we have: ​

// kubernetes config
configK8s := &civogo.KubernetesClusterConfig{
    NumTargetNodes: 5,
    Name: "existent-name",
}
// Send to create the cluster
resp, err := client.NewKubernetesClusters(configK8s)
if err != nil {
     if errors.Is(err, civogo.DatabaseKubernetesClusterDuplicateError) {
     // add some actions
     }
}

The following lines are new: ​

if err != nil {
     if errors.Is(err, civogo.DatabaseKubernetesClusterDuplicateError) {
     // add some actions
     }
}

In this way. we can make decisions faster based on known errors, and we know what to expect. There is also the option of being able to say this to account for some errors but not others: ​

if err != nil {
     if errors.Is(err, civogo.DatabaseKubernetesClusterDuplicateError) {
     // add some actions
     }
     if errors.Is(err, civogo.UnknownError) {
         // exit with error
     }
}

We can use UnknownError for errors that are not defined.

Contributing

If you want to get involved, we'd love to receive a pull request - or an offer to help over our KUBE100 Slack channel. Please see the contribution guidelines.

civogo's People

Contributors

alejandrojnm avatar alessandroargentieri avatar andyjeffries avatar bjoernakamanf avatar dependabot[bot] avatar dmajrekar avatar donnmyth avatar guineveresaenger avatar haardikdharma10 avatar hookenz avatar rberrelleza avatar realharshthakur avatar uzaxirr avatar vishalanarase avatar zulh-civo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

civogo's Issues

API return 500 when the casing of a field is wrong

When passing a field with capital case instead of lower case, the API returns a 500. I think it would be better if it returned a 400 error, with a message indicating the field that was wrong or missing.

Implementing More API Endpoints

Hello, I'm willing to contribute to this repo. Is there any endpoint/API that isn't implemented yet. Or any other good first issue i can contribute to.

Missing region assingment in some instance endpoints

When I was diagnosing civo/cli#136 and civo/cli#137, I noticed that the methods in this civogo's instance.go did not pass the region parameter to API server. Which giving error to CLI users.

I can confirm it by using Postman.

Reboot without region

image

Reboot with region

image

Stop without region

image

Stop with region

image

So I went deeper and check all methods in instance.go that are hitting /v2/instances/%s/* API endpoints and their status when get called by Civo CLI as follows:

# Method Status
1 SetInstanceTags Success
2 UpdateInstance Success
3 HardRebootInstance Failed
4 SoftRebootInstance Failed
5 StopInstance Failed
6 StartInstance Failed
7 GetInstanceConsoleURL Legacy
8 UpgradeInstance Success
9 MovePublicIPToInstance Legacy
10 SetInstanceFirewall Success

To fix this, all Failed methods above should have the following map as params:

map[string]string{
	"region": c.Region,
}

Full example:

civogo/instance.go

Lines 209 to 212 in 383002f

resp, err := c.SendPutRequest(fmt.Sprintf("/v2/instances/%s/tags", i.ID), map[string]string{
"tags": tags,
"region": c.Region,
})

GitHub Actions fails: GitHub Actions: The `set-env` command is deprecated and will be disabled soon.

GitHub Actions: The set-env command is deprecated and will be disabled soon.

From GitHub: https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/

Now the following error is being reported in my pipeline, for an alternative PR:

Error: Unable to process command '::set-env name=GOPATH::/home/runner/go' successfully.
8
Error: The set-env command is disabled. Please upgrade to using Environment Files or opt into unsecure command execution by setting the ACTIONS_ALLOW_UNSECURE_COMMANDS environment variable to true. For more information see: https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/
9
Error: Unable to process command '::add-path::/home/runner/go/bin' successfully.
10
Error: The add-path command is disabled. Please upgrade to using Environment Files or opt into unsecure command execution by setting the ACTIONS_ALLOW_UNSECURE_COMMANDS environment variable to true. For more information see: https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/

GitHub have new actions syntax

- name: setup env run: | echo "GOPATH=$(go env GOPATH)" >> $GITHUB_ENV echo "$(go env GOPATH)/bin" >> $GITHUB_PATH

Provide pricing of Civo resources through SDK

Hey there!

I'm part of the team behind Komiser, an open-source inventory platform that builds cloud asset inventories and breaks down costs at the resource level. Komiser integrates with multiple cloud providers, including Civo, and we currently use your official Go SDK to retrieve Civo resources. We currently calculate Civo resource pricing based on the public formula available on your landing page (see an example of how K8s resources are calculated). However, it would be more scalable/maintainable to obtain the price sheet through your SDK.

Happy to collaborate on this and contribute in bringing this feature to life :)

You can see a demo of how Civo integrates with Komiser here: https://youtu.be/jYHyQYbpkwk?t=2036

UnknownError is Raised when Using Invalid API Key

When accidentally setting an invalid API Key I receive:

martyn@macbook-pro civo-cli % civo --config .civo-test.json instance ls

Error: Listing instances failed with Unknow Error

Can we safely instead use AuthenticationFailedError?

Any request where the API Key is NOT ok results in:
{"result":"requires_authentication","status":401} (no bearer, empty bearer, invalid barer)

It is confusing to the user to issue an UnknownError

Also the response object uses: result, but the GoAPI assumes its called reason as per https://www.civo.com/api
This will also break the logic.

Kubernetes Cluster "generated_name" not available

Hi,

I'm trying to build autoscaling again and it would be nice to have the cluster's "generated_name" available via the Go module for easier conversion between the Civo API node name and the Kubernetes node name.

Thanks!

ListbyTag or filter options

Hi,

it would be nice, if we had the option to define filter options, when getting all instances.

At least giving the tags more relevance.

Thanks :)

Error in update, notes

When you try to update the obtines notes, an error is this:
&{failed instance_duplicate An instance with this name already exists, please choose another }
this is the code i'm using:

client, _ := civogo.NewClient(apiKey)
instance, _ := client.GetInstance("586f58df-be0c-4c4b-9640-3b73612d56ba")
instance.Notes = "test notes"

update, err := client.UpdateInstance(instance)
if err != nil {
	fmt.Println(err)
}

fmt.Println(update)

but if i change the hostanme too, then it works

client, _ := civogo.NewClient(apiKey)
instance, _ := client.GetInstance("586f58df-be0c-4c4b-9640-3b73612d56ba")
instance.Notes = "test notes"
instance.Hostname = "new_hostname"

update, err := client.UpdateInstance(instance)
if err != nil {
	fmt.Println(err)
}

fmt.Println(update)

Resize volume

I have a question:
I create a new volume and attach to one instance, can resize the volume??
in the UI you can't so i think it is not possible in the api

The second question:
This question is for the terraform provider, if you changed the size in the configuration of terraform, i can detach the volume, them resize and after attach again to the same instance @andyjeffries ?

query: testing with fake client

currently I am using the civogo client to get all the valid regions to validate users input.

// IsValidRegionCIVO validates the region code for CIVO
func isValidRegion(reg string) error {
	regions, err := civoClient.ListRegions()
	if err != nil {
		return err
	}
	for _, region := range regions {
		if region.Code == reg {
			return nil
		}
	}
	return fmt.Errorf("INVALID REGION")
}

now i want to test this function, via fakeCLient but it is returning fake output [{FAKE1 Fake testing region false {false false false false false false false false false} true}] regions. and using the original client requires creds

func (*civogo.Client).ListRegions() ([]civogo.Region, error)

ListRegions returns all load balancers owned by the calling API account

[`(civogo.Client).ListRegions` on pkg.go.dev](https://pkg.go.dev/github.com/civo/[email protected]#Client.ListRegions)

Add new option to the snapshot module

is it possible that when a snapshot has a cron defined, then the return of the api will have a field that says the next execution, but is it defined because it would be null, like this:

{
    "id": "0ca69adc-ff39-4fc1-8f08-d91434e86fac",
    "instance_id": "44aab548-61ca-11e5-860e-5cf9389be614",
    "hostname": "server1.prod.example.com",
    "template_id": "0b213794-d795-4483-8982-9f249c0262b9",
    "openstack_snapshot_id": null,
    "region": "lon1",
    "name": "my-instance-snapshot",
    "safe": 1,
    "size_gb": 0,
    "state": "in-progress",
    "cron_timing": "5 4 * * sun",
    "next_execution": "2020-04-19 04:05:00",
    "requested_at": null,
    "completed_at": null
  }

the new option will be this "next_execution": "2020-04-19 04:05:00" and if the cron is no't define them this value will be null.

Typo in UnknowError -> UnknownError

The generic exception is UnknowError, which is spelt wrong, can this safely be changed to UnknownError with affecting downstream clients

errors.go:924
return UnknowError

ListKubernetesClusters isn't returning the new ClusterType field

ClusterType is not being populated after calling ListAllKubernetesVersions. This means it's not possible to know what ClusterType to use when provisioning specific versions. We need this fix to correctly provision CIVO clusters in Portainer.

The problem is caused by the json tag on the KubernetesVersion type

It should be

ClusterType string `json:"clusterType,omitempty"

and not

ClusterType string `json:"cluster_type,omitempty"`

The rules of naming being.

To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. By default, object keys which don't have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).

In the case above, it uses the case-insensitive match. All the other fields following the same pattern even thought the API returns Pascal case field names.

example response from the versions API.

[
  {
    "Label": "1.22.2-k3s1",
    "Release": "1.22.2+k3s1",
    "Version": "1.22.2-k3s1",
    "Type": "deprecated",
    "Default": false,
    "ClusterType": "k3s"
  },
  {
    "Label": "1.20.2-k3s1",
    "Release": "1.20.2+k3s1",
    "Version": "1.20.2-k3s1",
    "Type": "deprecated",
    "Default": false,
    "ClusterType": "k3s"
  },
  {
    "Label": "1.21.2-k3s1",
    "Release": "1.21.2+k3s1",
    "Version": "1.21.2-k3s1",
    "Type": "deprecated",
    "Default": false,
    "ClusterType": "k3s"
  },
  {
    "Label": "1.24.4-k3s1",
    "Release": "1.24.4+k3s1",
    "Version": "1.24.4-k3s1",
    "Type": "development",
    "Default": false,
    "ClusterType": "k3s"
  },
  {
    "Label": "1.22.11-k3s1",
    "Release": "1.22.11+k3s1",
    "Version": "1.22.11-k3s1",
    "Type": "deprecated",
    "Default": false,
    "ClusterType": "k3s"
  },
  {
    "Label": "1.23.6-k3s1",
    "Release": "1.23.6+k3s1",
    "Version": "1.23.6-k3s1",
    "Type": "stable",
    "Default": true,
    "ClusterType": "k3s"
  },
  {
    "Label": "talos-v1.2.8",
    "Release": "1.2.8",
    "Version": "1.25.5",
    "Type": "stable",
    "Default": true,
    "ClusterType": "talos"
  },
  {
    "Label": "1.25.0-k3s1",
    "Release": "1.25.0+k3s1",
    "Version": "1.25.0-k3s1",
    "Type": "development",
    "Default": false,
    "ClusterType": "k3s"
  },
  {
    "Label": "1.20.0-k3s1",
    "Release": "1.20.0+k3s1",
    "Version": "1.20.0-k3s1",
    "Type": "deprecated",
    "Default": false,
    "ClusterType": "k3s"
  }
]

More documentation

@andyjeffries is possible to add more documentation in the api of kubernetes the result show "configuration": {} inside of installed_applications, but what is inside of configuration, in order to implement the struct for that, it is possible to know the content

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.