resingo

package module
v0.0.0-...-32ad94e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2016 License: MIT Imports: 17 Imported by: 0

README

resingo GoDoc Go Report CardBuild StatusCoverage Status

The unofficial golang sdk for resin.io

MAINTAINER WANTED I no longer work with resin devices, so I don't have time to put into this. If you are interested in maintaining this please let me know! Thanks.

what is resin and what is resingo?

Resin is a service that brings the benefits of linux containers to IoT. It enables iterative development, deployment and management of devices at scale. Please go to their website for more information.

Resingo, is a standard development kit for resin, that uses the Go(Golang) programming language. This library, provides nuts and bolts necessary for developers to interact with resin service using the Go programming language.

This library is full featured, well tested and well designed. If you find anything that is missing please open an issssue

This is the laundry list of things you can do.

  • Applications

  • Get all applications

  • Get application by name

  • Get application by application id

  • Create Application

  • Delete application

  • Generate application API key

  • Devices

  • Get all devices

  • Get all devices for a given device name

  • Get device by UUID

  • Get device by name

  • Get application name by device uuid

  • Check if the device is online or not

  • Get local IP address of the device

  • Remove/Delete device

  • Rename device

  • Note a device

  • Generate device UUID

  • Register device

  • Enable device url

  • Disable device url

  • Move device

  • Check device status

  • Identify device by blinkig

  • Environment

  • Device

  • Get all device environment variables

  • Create a device environment variable

  • Update device environment variable

  • Remove/Delete device environment variable

  • Application

  • Get all application environment variables

  • Create application environment variable

  • Update application environment variable

  • Remove application environment variable

  • Keys

  • Get all ssh keys

  • Get a dingle ssh key

  • Remove ssh key

  • Create ssh key

  • Os

    • Download Os Image
  • Config

  • Get all configurations

  • Logs

  • Subscribe to device logs

  • Retrieve historical logs

  • Supervisor

  • Reboot

Introduction

Installation

go get github.com/gernest/resingo

Design philosophy

Naming convention

The library covers different componets of the resin service namely device, application, os ,environment and keys.

Due to the nature of this lirary to use functions rather than attach methods to the relevant structs. We use a simple strategy of naming functions that operates for the different components. This is by adding Prefix that represent the resin component.

The following is the Prefix table that shows all the prefix used to name the functions. For example DevGetAll is a function that retrives all devices and AppGetAll is a function that retrieves all App;ications.

component function prefix
Device Dev
Application App
EnvironMent Env
Os Os
Keys Key
Functions over methods

This library favors functions to provide functionality that interact with resin. All this functions accepts Context as the first argument, and can optionally accepts other arguments which are function specific( Note that this Context is defined in this libary, don't mistook it for the context.Context).

The reason behind this is to provide composability and making the codebase clean. Also it is much easier for testing.

Usage


package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gernest/resingo"
)

func main() {

	// We need the context from which we will be talking to the resin API
	ctx := &resingo.Context{
		Client: &http.Client{},
		Config: &resingo.Config{
			Username: "Your resing username",
			Password: "your resubn password",
		},
	}

	/// There are two ways to authenticate the context ctx.

	// Authenticate with credentials i.e Username and password
	err := resingo.Login(ctx, resingo.Credentials)
	if err != nil {
		log.Fatal(err)
	}

	// Or using authentication token, which you can easily find on your resin
	// dashboard
	err = resingo.Login(ctx, resingo.AuthToken, "Tour authentication token goes here")
	if err != nil {
		log.Fatal(err)
	}

	// Now the ctx is authenticated you can pass it as the first arument to any
	// resingo API function.
	//
	// The ctx is safe for concurrent use

	// Get All your applications
	apps, err := resingo.AppGetAll(ctx)
	if err != nil {
		log.Fatal(err)
	}
	for _, a := range apps {
		fmt.Println(*a)
	}
}

Contributing

This requires go1.7+

Running tests will require a valid resin account . You need to set the following environment variables before running the make command.

export RESINTEST_EMAIL=
export RESINTEST_PASSWORD=
export RESINTEST_USERNAME=
export RESINTEST_REALDEVICE_UUID=

The names are self explanatory. To avoid typing them all the time, you can write them into a a file named .env which stays at the root of this project, the test script will automatically source it for you.

All contributions are welcome.

Author

twitter @gernesti

Licence

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrBadToken = errors.New("resingo: bad session token")

ErrBadToken error returned when the resin session token is bad.

View Source
var ErrDeviceNotFound = errors.New("resingo: device not found")

ErrDeviceNotFound is returned when there is no device returned from an API call for devices.

We assume that, a valid API call will alwayss return with valid results, so lack of any matching devices means we didn't find anything.

NOTE: This should have been handled by resin api. Probably with status codes and the response body indicating nothing was dound.

View Source
var ErrMissingCredentials = errors.New("resingo: missing credentials( username or password)")

ErrMissingCredentials error returned when either username or password is missing

View Source
var ErrUnkownAuthType = errors.New("resingo: unknown authentication type")

ErrUnkownAuthType error returned when the type of authentication is not supported.

Functions

func AgentReboot

func AgentReboot(ctx *Context, devID, appID int64, force bool) error

AgentReboot reboots the device

func AppDelete

func AppDelete(ctx *Context, id int64) (bool, error)

AppDelete removes the application with the given id

func AppGetAPIKey

func AppGetAPIKey(ctx *Context, name string) ([]byte, error)

AppGetAPIKey returns the application with the given api key

func Authenticate

func Authenticate(ctx *Context, typ AuthType, authToken ...string) (string, error)

Authenticate authenticates the client and returns the Auth token. See Login if you want to save the token in the client. This function does not save the authentication token and user detals.

func DevBlink(ctx *Context, uuid string) error

DevBlink identifies the device by blinking.

func DevDelete

func DevDelete(ctx *Context, id int64) error

DevDelete deletes the device with the given id

func DevDisableURL

func DevDisableURL(ctx *Context, uuid string) error

DevDisableURL diables the deice url, making it not accessible via the web.

func DevEnableURL

func DevEnableURL(ctx *Context, uuid string) error

DevEnableURL enables the device url. This allows the device to be accessed anywhere using the url which uses resin vpn.

NOTE: It is awskward to retrurn OK rather than the url which was enabled.

func DevIsOnline

func DevIsOnline(ctx *Context, uuid string) (bool, error)

DevIsOnline return true if the device with uuid is online and false otherwise. Any errors encountered is returned too.

func DevMove

func DevMove(ctx *Context, id int64, appID int64) error

DevMove moves the device to a different application

func DevNote

func DevNote(ctx *Context, id int64, note string) error

DevNote add note to the device

func DevRename

func DevRename(ctx *Context, uuid, newName string) error

DevRename renames the device with uuid to nwName

func Encode

func Encode(q url.Values) string

Encode encode properly the request params for use with resin API.

Encode tartegts the filter param, which for some reasom(based on OData) is supposed to be $filter and not filter. The value specified by the eq param key is combined with the value from the fileter key to produce the $filter value string.

Any other url params are encoded by the default encoder from url.Values.Encoder. TODO: check a better way to encode OData url params.

func EnvAppDelete

func EnvAppDelete(ctx *Context, id int64) error

EnvAppDelete deletes application environment variable

func EnvAppUpdate

func EnvAppUpdate(ctx *Context, id int64, value string) error

EnvAppUpdate updates an existing application environmant variable

func EnvDevDelete

func EnvDevDelete(ctx *Context, id int64) error

EnvDevDelete deketes device environment variable

func EnvDevUpdate

func EnvDevUpdate(ctx *Context, id int64, value string) error

EnvDevUpdate updates environment variable for device. The id is for the environmant variable.

func GenerateUUID

func GenerateUUID() (string, error)

GenerateUUID generates uuid suitable for resin devices

func KeyRemove

func KeyRemove(ctx *Context, id int64) error

KeyRemove removes the public key with the given id

func Login

func Login(ctx *Context, authTyp AuthType, authToken ...string) error

Login authenticates the contextand stores the session token. This function checks the validity of the session token before saving it.

The call to ctx.IsLoged() should return true if the returned error is nil.

func ValidToken

func ValidToken(tok string) bool

ValidToken return true if tok is avalid token

Types

type APIVersion

type APIVersion int

APIVersion is the version of resin API

const (
	VersionOne APIVersion = iota
	VersionTwo
	VersionThree
)

supported resin API versions

func (APIVersion) String

func (v APIVersion) String() string

type AppEnv

type AppEnv struct {
	ID          int64  `json:"id"`
	Name        string `json:"name"`
	Value       string `json:"value"`
	Application struct {
		ID       int64 `json:"__id"`
		Deferred struct {
			URI string `json:"uri"`
		} `json:"__deferred"`
	} `json:"application"`
	Metadata struct {
		URI  string `json:"uri"`
		Type string `json:"type"`
	} `json:"__metadata"`
}

AppEnv application environment variable

func EnvAppCreate

func EnvAppCreate(ctx *Context, id int64, key, value string) (*AppEnv, error)

EnvAppCreate creates a newapplication environment variable

func EnvAppGetAll

func EnvAppGetAll(ctx *Context, id int64) ([]*AppEnv, error)

EnvAppGetAll retruns all environment variables for application

type Application

type Application struct {
	ID         int64  `json:"id"`
	Name       string `json:"app_name"`
	Repository string `json:"git_repository"`
	Metadata   struct {
		URI  string `json:"uri"`
		Type string `json:"type"`
	} `json:"__metadata"`
	DeviceType string `json:"device_type"`
	User       User   `json:"user"`
	Commit     string `json:"commit"`
}

Application holds information about the application that is running on resin.

func AppCreate

func AppCreate(ctx *Context, name string, typ DeviceType) (*Application, error)

AppCreate creates a new application with the given name

func AppGetAll

func AppGetAll(ctx *Context) ([]*Application, error)

AppGetAll retrieves all applications that belog to the user in the given context.

For this to work, the context should be authorized, probably using the Login function.

func AppGetByID

func AppGetByID(ctx *Context, id int64) (*Application, error)

AppGetByID returns application with the given id

func AppGetByName

func AppGetByName(ctx *Context, name string) (*Application, error)

AppGetByName returns the application with the giveb name.

func DevGetApp

func DevGetApp(ctx *Context, uuid string) (*Application, error)

DevGetApp returns the application in which the device belongs to. This function is convenient only when you are interested on other information about the application.

If your intention is only to retrieve the applicayion id, then just use this instead.

dev,err:=DevGetByUUID(ctx,<uuid goes here>)
if err!=nil{
	//handle error error
}
// you can now access the application id like this
fmt.Println(dev.Application.ID

type AuthType

type AuthType int

AuthType is the authentication type that is used to authenticate with a resin.io api.

const (
	Credentials AuthType = iota
	AuthToken
)

supported authentication types

type Config

type Config struct {
	AuthToken string
	Username  string
	Password  string
	APIKey    string

	ResinEndpoint string
	ResinVersion  APIVersion
	// contains filtered or unexported fields
}

Config is the configuration object for the Client

func (*Config) APIEndpoint

func (c *Config) APIEndpoint(endpoint string) string

APIEndpoint returns a url that points to the given endpoint. This adds the resin.io api host and version.

func (*Config) IsValidToken

func (c *Config) IsValidToken(tok string) bool

IsValidToken return true if the token tok is a valid resin session token.

This method ecodes the token. A token that can't be doced is bad token. Any token that has expired is also a bad token.

func (*Config) SaveToken

func (c *Config) SaveToken(tok string) error

SaveToken saves token, to the current Configuration object.

func (*Config) UserID

func (c *Config) UserID() int64

UserID returns the user id.

type Context

type Context struct {
	Client HTTPClient
	Config *Config
}

Context holds information necessary to make a call to the resin API

type Device

type Device struct {
	ID            int64  `json:"id"`
	Name          string `json:"name"`
	WebAccessible bool   `json:"is_web_accessible"`
	Type          string `json:"device_type"`
	Application   struct {
		ID       int64 `json:"__id"`
		Metadata struct {
			URI string `json:"uri"`
		} `json:"__deferred"`
	} `json:"application"`
	UUID                  string    `json:"uuid"`
	User                  User      `json:"user"`
	Actor                 int64     `json:"actor"`
	IsOnline              bool      `json:"is_online"`
	Commit                string    `json:"commit"`
	Status                string    `json:"status"`
	LastConnectivityEvent null.Time `json:"last_connectivity_event"`
	IP                    string    `json:"ip_address"`
	VPNAddr               string    `json:"vpn_address"`
	PublicAddr            string    `json:"public_address"`
	SuprevisorVersion     string    `json:"supervisor_version"`
	Note                  string    `json:"note"`
	OsVersion             string    `json:"os_version"`
	Location              string    `json:"location"`
	Longitude             string    `json:"longitude"`
	Latitude              string    `json:"latitude"`
	LogsChannel           string    `json:"logs_channel"`
}

Device represent the information about a resin device

func DevGetAll

func DevGetAll(ctx *Context) ([]*Device, error)

DevGetAll returns all devices that belong to the user who authorized the context ctx.

func DevGetAllByApp

func DevGetAllByApp(ctx *Context, appID int64) ([]*Device, error)

DevGetAllByApp returns all devices that are registered to the application with the given appID

func DevGetByName

func DevGetByName(ctx *Context, name string) (*Device, error)

DevGetByName returns the device with the given name

func DevGetByUUID

func DevGetByUUID(ctx *Context, uuid string) (*Device, error)

DevGetByUUID returns the device with the given uuid.

func DevRegister

func DevRegister(ctx *Context, appName, uuid string) (*Device, error)

DevRegister registers the device with uuid to the the application with name appName.

type DeviceType

type DeviceType int

DeviceType is the identity of the the device that is supported by resin.

const (
	Artik10 DeviceType = iota
	Artik5
	BeagleboneBlack
	HumingBoard
	IntelAdison
	IntelNuc
	Nitrogen6x
	OdroidC1
	OdroidXu4
	Parallella
	RaspberryPi
	RaspberryPi2
	RaspberryPi3
	Ts4900
	Ts700
	ViaVabx820Quad
	ZyncXz702
)

supported devices

func (DeviceType) String

func (d DeviceType) String() string

type Env

type Env struct {
	ID     int64  `json:"id"`
	Name   string `json:"env_var_name"`
	Value  string `json:"value"`
	Device struct {
		ID       int64 `json:"__id"`
		Deferred struct {
			URI string `json:"uri"`
		} `json:"__deferred"`
	} `json:"device"`
	Metadata struct {
		URI  string `json:"uri"`
		Type string `json:"type"`
	} `json:"__metadata"`
}

Env contains the response for device environment variable

func EnvDevCreate

func EnvDevCreate(ctx *Context, id int64, key, value string) (*Env, error)

EnvDevCreate creates environment variable for the device

func EnvDevGetAll

func EnvDevGetAll(ctx *Context, id int64) ([]*Env, error)

EnvDevGetAll get all environment variables for the device

type HTTPClient

type HTTPClient interface {
	Do(*http.Request) (*http.Response, error)
	Post(url string, bodyTyp string, body io.Reader) (*http.Response, error)
}

HTTPClient is an interface for a http clinet that is used to communicate with the resin API

type Key

type Key struct {
	ID        int64  `json:"id"`
	Title     string `json:"title"`
	PublicKey string `json:"public_key"`
	User      struct {
		ID       int64 `json:"__id"`
		Deferred struct {
			URI string `json:"uri"`
		} `json:"__deferred"`
	} `json:"user"`
	Metadata struct {
		URI  string `json:"uri"`
		Type string `json:"type"`
	} `json:"__metadata"`
	CreatedAt time.Time `json:"created_at"`
}

Key is a user public key on resin

func KeyCreate

func KeyCreate(ctx *Context, userID int64, key, title string) (*Key, error)

KeyCreate creates a public key for the user with given userID

func KeyGetAll

func KeyGetAll(ctx *Context) ([]*Key, error)

KeyGetAll retrives all key for the user who authenticated ctx.

func KeyGetByID

func KeyGetByID(ctx *Context, id int64) (*Key, error)

KeyGetByID retrives public key with the given id

type Logs

type Logs struct {
	// contains filtered or unexported fields
}

Logs streams resin device logs

Resin uses pubnub service for logs. Unfortunate the API for pubnub sucks big time. This Limits the API for this struct too.

func NewLogs

func NewLogs(ctx *Context) (*Logs, error)

NewLogs returns a new Logs instace which is initialized to support streaming logs from pubnub.

func (*Logs) Close

func (l *Logs) Close()

Close stops streaming device logs.

func (*Logs) GetChannel

func (l *Logs) GetChannel(uuid string) (string, error)

GetChannel returns the device logs channel for the device with given uuid.. The value is not cached, so this is stateless. This allows to use the same Lofs instance to syvscribe to multiple devices in different goroutines without race conditions.

func (*Logs) Log

func (l *Logs) Log(uuid string, out io.Writer) error

Log streams logs go out. This is blocking opretation, you should run this in a gorouting and call Log.Close when you are done acceping writes to out.

func (*Logs) Subscribe

func (l *Logs) Subscribe(uuid string) (
	chan []byte, chan []byte, error,
)

Subscribe subscribe to device logs

type Repository

type Repository struct {
	URL    string
	Commit string
}

Repository is a resin remote repository

type ResinConfig

type ResinConfig struct {
	SocialProviders    []string `json:"supportedSocialProviders"`
	SignupCodeRequired bool     `json:"signupCodeRequired"`
	MixPanelToken      string   `json:"mixpanelToken"`
	KeenProjectID      string   `json:"keenProjectId"`
	KeenReadKey        string   `json:"keenReadKey"`
	DeviceURLBase      string   `json:"deviceUrlsBase"`
	GitServerURL       string   `json:"gitServerUrl"`
	ImageMakerURL      string   `json:"imgMakerUrl"`
	AdminURL           string   `json:"adminUrl"`
	DebugEnabled       bool     `json:"debugEnabled"`
	PubNub             struct {
		PubKey string `json:"publish_key"`
		SubKey string `json:"subscribe_key"`
	} `json:"pubnub"`
	GoogleAnalytics struct {
		ID   string `kson:"id"`
		Site string `json:"site"`
	} `json:"ga"`

	DeviceTypes []struct {
		Slug              string   `json:"slug"`
		Version           int      `json:"version"`
		Aliases           []string `json:"aliases"`
		Name              string   `json:"name"`
		Arch              string   `json:"arch"`
		State             string   `json:"state"`
		StateInstructions struct {
			PostProvisioning []string `json:"postProvisioning"`
		} `json:"stateInstructions"`
		//Instructions []string `json:"instructions"`
		SupportsBlink bool `json:"supportsBlink"`
		Yocto         struct {
			Machine       string `json:"machine"`
			Image         string `json:"image"`
			FSType        string `json:"fstype"`
			Version       string `json:"version"`
			DeployArtfact string `json:"deployArtfact"`
			Compressed    bool   `json:"compressed"`
		} `json:"yocto"`
		Options []struct {
			IsGroup bool   `json:"isGroup"`
			Name    string `json:"name"`
			Message string `json:"message"`
			Options []struct {
				Name    string   `json:"name"`
				Message string   `json:"message"`
				Type    string   `json:"type"`
				CHoices []string `json:"choices"`
			} `json:"options"`
		} `json:"options"`
		Configuration struct {
			Config struct {
				Partition struct {
					Primary int `json:"primary"`
				} `json:"partition"`
			} `json:"config"`
		} `json:"configuration"`
		Initialization struct {
			Options []struct {
				Name    string `json:"name"`
				Message string `json:"message"`
				Type    string `json:"type"`
			} `json:"options"`
			Operations []struct {
				Command string `json:"command"`
			} `json:"operations"`
		} `json:"initialization"`
		BuildID string `json:"buildId"`
	} `json:"deviceTypes"`
}

ResinConfig resin configuration

func ConfigGetAll

func ConfigGetAll(ctx *Context) (*ResinConfig, error)

ConfigGetAll return resin congiguration

type TokenClain

type TokenClain struct {
	Username string `json:"username"`
	UserID   int64  `json:"id"`
	Email    string `json:"email"`
	jwt.StandardClaims
}

TokenClain are the values that are encoded into a session token from resin.io.

It embeds jst.StandardClaims, so as to help with Verification of expired data. Resin doens't do claim verification :(.

func ParseToken

func ParseToken(tok string) (*TokenClain, error)

ParseToken parses the given token and extracts the claims emcode into it. This function uses JWT method to parse the token, with verification of claims turned off.

type User

type User struct {
	ID       int64 `json:"__id"`
	Metadata struct {
		URI string `json:"uri"`
	} `json:"__deferred"`
}

User a resin user

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL