piazza

package
v0.0.0-...-fdf610b Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2018 License: Apache-2.0 Imports: 21 Imported by: 14

Documentation

Index

Constants

View Source
const (
	// ContentTypeJSON is the http content-type for JSON.
	ContentTypeJSON = "application/json"

	// ContentTypeText is the http content-type for plain text.
	ContentTypeText = "text/plain"
)
View Source
const DefaultDomain = ".venicegeo.io"
View Source
const DefaultElasticsearchAddress = "localhost:9200"
View Source
const DefaultKafkaAddress = "localhost:9092"
View Source
const DefaultProtocol = "http"
View Source
const DefaultPzLoggerAddress = "localhost:14600"
View Source
const DefaultPzUuidgenAddress = "localhost:14800"
View Source
const GET, PUT, POST, DELETE, HEAD = "GET", "PUT", "POST", "DELETE", "HEAD"

Variables

View Source
var EndpointPrefixes = map[ServiceName]string{
	PzDiscover:          "",
	PzElasticSearch:     "",
	PzKafka:             "",
	PzLogger:            "",
	PzUuidgen:           "",
	PzWorkflow:          "",
	PzsvcHello:          "",
	PzServiceController: "",
	PzMetrics:           "",
	PzIdam:              "",
}
View Source
var HealthcheckEndpoints = map[ServiceName]string{
	PzDiscover:          "",
	PzElasticSearch:     "",
	PzKafka:             "",
	PzLogger:            "/",
	PzUuidgen:           "/",
	PzWorkflow:          "/",
	PzsvcHello:          "/",
	PzServiceController: "",
	PzMetrics:           "/",
	PzIdam:              "",
}
View Source
var JsonResponseDataTypes = map[string]string{}
View Source
var LocalPortNumbers = map[ServiceName]string{
	PzWorkflow:          "20000",
	PzLogger:            "20001",
	PzUuidgen:           "20002",
	PzDiscover:          "20003",
	PzElasticSearch:     "20004",
	PzServiceController: "20005",
	PzMetrics:           "20006",
	PzKafka:             "20007",
	PzsvcHello:          "20008",
	PzGoCommon:          "20009",
	PzGoCommonTest:      "20010",
	PzIdam:              "20011",
}

Functions

func CharAt

func CharAt(str string, index int) string

func GetApiKey

func GetApiKey(pzserver string) (string, error)

GetApiKey retrieves the Pz API key for the given server, in this order:

(1) if $PZKEY present, use that (2) if ~/.pzkey exists, use that (3) error

And no, we don't uspport Windows.

func GetApiServer

func GetApiServer() (string, error)

TODO: just for backwards compatability

func GetBasicAuthHeader

func GetBasicAuthHeader(username, password string) [2]string

func GetExternalIP

func GetExternalIP() (string, error)

GetExternalIP returns the "best"(?) IP address we can reasonably get. see: http://stackoverflow.com/a/23558495

func GetPiazzaServiceUrl

func GetPiazzaServiceUrl(serviceName ServiceName) (string, error)

GetServiceServer returns the host name of the given service, based on $PZSERVER.

func GetPiazzaUrl

func GetPiazzaUrl() (string, error)

GetPiazzaServer returns the URL of the $PZSERVER host, i.e. the public entry point.

func GetValueFromHeader

func GetValueFromHeader(header http.Header, field string) string

func GetVarsFromStruct

func GetVarsFromStruct(struc interface{}) (map[string]interface{}, error)

func GetVarsFromStructSkip

func GetVarsFromStructSkip(struc interface{}, skipMaps map[string]bool) (map[string]interface{}, error)

func GinReturnJson

func GinReturnJson(c *gin.Context, resp *JsonResponse)

func HTTP

func HTTP(requestType, url string, headers [][2]string, toSend io.Reader) (int, []byte, http.Header, error)

func HTTPDelete

func HTTPDelete(url string) (*http.Response, error)

Delete, because there is no http.Delete.

func HTTPPut

func HTTPPut(url string, contentType string, body io.Reader) (*http.Response, error)

Put, because there is no http.Put.

func InsertString

func InsertString(str, insert string, index int) string

func RemoveWhitespace

func RemoveWhitespace(str string) string

func RequestAuthZAccess

func RequestAuthZAccess(idamURL string, actor string) (authorized bool, err error)

action auditString

func SplitString

func SplitString(str string, whereToSplit int) (string, string)

func StructInterfaceToString

func StructInterfaceToString(stru interface{}) (string, error)

func StructStringToInterface

func StructStringToInterface(stru string) (interface{}, error)

func UnmarshalNumber

func UnmarshalNumber(r io.Reader, v interface{}) error

func ValidUuid

func ValidUuid(uuid string) bool

func ValueIsValidArray

func ValueIsValidArray(value interface{}) bool

func WaitForService

func WaitForService(name ServiceName, url string) error

func WaitForServiceToDie

func WaitForServiceToDie(name ServiceName, url string) error

Types

type FlightCheck

type FlightCheck interface {
	Preflight(verb string, url string, obj string) error
	Postflight(code int, obj string) error
}

type GenericServer

type GenericServer struct {
	Sys *SystemConfig
	// contains filtered or unexported fields
}

GenericServer is the basic framework for standing up a gin-based server. It has methods to Start and Stop as well as to define the routing paths.

func (*GenericServer) Configure

func (server *GenericServer) Configure(routeData []RouteData) error

Configure will take the give RouteData and register them with the server.

func (*GenericServer) Start

func (server *GenericServer) Start() (chan error, error)

Start will start the service. You must call Configure first.

func (*GenericServer) Stop

func (server *GenericServer) Stop() error

Stop will request the server to shutdown. It will wait for the service to die before returning.

type HeaderBuilder

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

func NewHeaderBuilder

func NewHeaderBuilder() *HeaderBuilder

func (*HeaderBuilder) AddBasicAuth

func (builder *HeaderBuilder) AddBasicAuth(username, password string) *HeaderBuilder

func (*HeaderBuilder) AddHeader

func (builder *HeaderBuilder) AddHeader(key, value string) *HeaderBuilder

func (*HeaderBuilder) AddJsonContentType

func (builder *HeaderBuilder) AddJsonContentType() *HeaderBuilder

func (*HeaderBuilder) GetHeader

func (builder *HeaderBuilder) GetHeader() [][2]string

type Http

type Http struct {
	FlightCheck FlightCheck
	ApiKey      string
	BaseUrl     string
	User        string
	Pass        string
}

func (*Http) Delete

func (h *Http) Delete(endpoint string, output interface{}) (int, error)

expects endpoint to return nothing

func (*Http) Get

func (h *Http) Get(endpoint string, output interface{}) (int, error)

expects endpoint to return JSON

func (*Http) Get2

func (h *Http) Get2(endpoint string, input interface{}, output interface{}) (int, error)

func (*Http) Post

func (h *Http) Post(endpoint string, input interface{}, output interface{}) (int, error)

expects endpoint to take in and return JSON

func (*Http) Put

func (h *Http) Put(endpoint string, input interface{}, output interface{}) (int, error)

expects endpoint to take in and return JSON

func (*Http) PzDelete

func (h *Http) PzDelete(endpoint string) *JsonResponse

func (*Http) PzGet

func (h *Http) PzGet(endpoint string) *JsonResponse

func (*Http) PzGet2

func (h *Http) PzGet2(endpoint string, input interface{}) *JsonResponse

func (*Http) PzPost

func (h *Http) PzPost(endpoint string, input interface{}) *JsonResponse

func (*Http) PzPut

func (h *Http) PzPut(endpoint string, input interface{}) *JsonResponse

func (*Http) Verb

func (h *Http) Verb(verb string, endpoint string, input interface{}, output interface{}) (int, error)

expects endpoint to take in and return JSON

type HttpQueryParams

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

HttpQueryParams holds a list of the query parameters of a URL, e.g.

...?count=8&foo=bar

We don't want to pass http.Request objects into the Services classes (and certainly not a gin.Context!), and we need this kind of information a lot, so we'll keep a special data structure which actually understands the semantics as well as the syntax.

func NewQueryParams

func NewQueryParams(request *http.Request) *HttpQueryParams

NewQueryParams creates an HttpQueryParams object from an http.Request.

func (*HttpQueryParams) AddString

func (params *HttpQueryParams) AddString(key string, value string)

AddString adds a key and string value to the parameter set, e.g. "?foo=bar".

func (*HttpQueryParams) AddTime

func (params *HttpQueryParams) AddTime(key string, value time.Time)

AddTime adds a key and time value to the parameter set.

func (*HttpQueryParams) GetAfter

func (params *HttpQueryParams) GetAfter(defalt time.Time) (time.Time, error)

GetAfter retrieves the value of the "after" parameter.

func (*HttpQueryParams) GetAsID

func (params *HttpQueryParams) GetAsID(key string, defalt string) (Ident, error)

GetAsID retrieves the (string) value of a key from parameter set and returns it as an Ident.

func (*HttpQueryParams) GetAsInt

func (params *HttpQueryParams) GetAsInt(key string, defalt int) (int, error)

GetAsInt retrieves the (string) value of a key from parameter set and returns it as an int.

func (*HttpQueryParams) GetAsSortOrder

func (params *HttpQueryParams) GetAsSortOrder(key string, defalt SortOrder) (SortOrder, error)

GetAsSortOrder retrieves the (string) value of a key from parameter set and returns it as SortOrder value.

func (*HttpQueryParams) GetAsString

func (params *HttpQueryParams) GetAsString(key string, defalt string) (string, error)

GetAsString retrieves the (string) value of a key from parameter set and returns it.

func (*HttpQueryParams) GetAsTime

func (params *HttpQueryParams) GetAsTime(key string, defalt time.Time) (time.Time, error)

GetAsTime retrieves the (string) value of a key from parameter set and returns it as time value.

func (*HttpQueryParams) GetBefore

func (params *HttpQueryParams) GetBefore(defalt time.Time) (time.Time, error)

GetBefore retrieves the value of the "before" parameter.

func (*HttpQueryParams) GetCount

func (params *HttpQueryParams) GetCount(defalt int) (int, error)

GetCount retrieves the value of the "count" parameter.

func (*HttpQueryParams) GetPage

func (params *HttpQueryParams) GetPage(defalt int) (int, error)

GetPage retrieves the value of the "page" parameter.

func (*HttpQueryParams) GetPerPage

func (params *HttpQueryParams) GetPerPage(defalt int) (int, error)

GetPerPage retrieves the value of the "perPage" parameter.

func (*HttpQueryParams) GetSortBy

func (params *HttpQueryParams) GetSortBy(defalt string) (string, error)

GetSortBy retrieves the value of the "sortBy" parameter.

func (*HttpQueryParams) GetSortOrder

func (params *HttpQueryParams) GetSortOrder(defalt SortOrder) (SortOrder, error)

GetSortOrder retrieves the value of the "order" parameter.

func (*HttpQueryParams) String

func (params *HttpQueryParams) String() string

String returns the parameter list expressed in URL style.

type Ident

type Ident string

Ident is the type used for representing ID values.

const NoIdent Ident = ""

NoIdent is the "empty" ID value.

func (Ident) String

func (id Ident) String() string

String returns an id as a string.

type JsonPagination

type JsonPagination struct {
	Count   int       `json:"count"` // only used when writing output
	Page    int       `json:"page"`
	PerPage int       `json:"perPage"`
	SortBy  string    `json:"sortBy"`
	Order   SortOrder `json:"order"`
}

JsonPagination is the Piazza model for pagination json responses.

func NewJsonPagination

func NewJsonPagination(params *HttpQueryParams) (*JsonPagination, error)

NewJsonPagination creates a JsonPagination object. The default values will be overwritten with any appropriate values from the params list.

func (*JsonPagination) EndIndex

func (p *JsonPagination) EndIndex() int

EndIndex returns the index number of the last element to be used.

func (*JsonPagination) StartIndex

func (p *JsonPagination) StartIndex() int

StartIndex returns the index number of the first element to be used.

func (*JsonPagination) String

func (p *JsonPagination) String() string

String returns a URL-style string of the pagination settings.

func (*JsonPagination) SyncPagination

func (format *JsonPagination) SyncPagination(dslString string) (string, error)

type JsonResponse

type JsonResponse struct {
	StatusCode int `json:"statusCode" binding:"required"`

	// only 2xxx -- Data is required (and Type too)
	// Type is a string, taken from the Java model list
	Type       string          `json:"type,omitempty"`
	Data       interface{}     `json:"data,omitempty" binding:"required"`
	Pagination *JsonPagination `json:"pagination,omitempty"` // optional

	// only 4xx and 5xx -- Message is required
	Message string        `json:"message,omitempty"`
	Origin  string        `json:"origin,omitempty"` // optional
	Inner   *JsonResponse `json:"inner,omitempty"`  // optional

	// optional
	Metadata interface{} `json:"metadata,omitempty"`
}

func (*JsonResponse) ExtractData

func (resp *JsonResponse) ExtractData(output interface{}) error

given a JsonResponse object returned from an http call, and with Data set convert it to the given output type (formerly called SuperConverter)

func (*JsonResponse) IsError

func (resp *JsonResponse) IsError() bool

func (*JsonResponse) SetType

func (resp *JsonResponse) SetType() error

func (*JsonResponse) String

func (resp *JsonResponse) String() string

func (*JsonResponse) ToError

func (resp *JsonResponse) ToError() error

type JsonString

type JsonString string

JsonString is the type used to represent JSON values.

type RouteData

type RouteData struct {
	Verb    string
	Path    string
	Handler gin.HandlerFunc
}

RouteData describes one server route: which http verb, the path string, and the handler to use.

type ServiceName

type ServiceName string
const (
	PzDiscover          ServiceName = "pz-discover"
	PzElasticSearch     ServiceName = "pz-elasticsearch"
	PzGoCommon          ServiceName = "PZ-GOCOMMON"     // not a real service, just for testing
	PzGoCommonTest      ServiceName = "PZ-GOCOMMONTEST" // not a real service, just for testing
	PzKafka             ServiceName = "pz-kafka"
	PzLogger            ServiceName = "pz-logger"
	PzUuidgen           ServiceName = "pz-uuidgen"
	PzWorkflow          ServiceName = "pz-workflow"
	PzsvcHello          ServiceName = "pzsvc-hello"
	PzServiceController ServiceName = "pz-servicecontroller"
	PzMetrics           ServiceName = "pz-metrics"
	PzIdam              ServiceName = "pz-idam"
)

type ServicesMap

type ServicesMap map[ServiceName]string

type SimpleFlightCheck

type SimpleFlightCheck struct {
	NumPreflights  int
	NumPostflights int
}

func (*SimpleFlightCheck) Postflight

func (fc *SimpleFlightCheck) Postflight(code int, obj string) error

func (*SimpleFlightCheck) Preflight

func (fc *SimpleFlightCheck) Preflight(verb string, url string, obj string) error

type SortOrder

type SortOrder string

SortOrder indicates ascending (1,2,3) or descending (3,2,1) order.

const (
	// SortOrderAscending is for "a, b, c, ..."
	SortOrderAscending SortOrder = "asc"

	// SortOrderDescending is for "z, y, x, ..."
	SortOrderDescending SortOrder = "desc"
)

type SystemConfig

type SystemConfig struct {
	// our own service
	Name    ServiceName
	Address string
	BindTo  string

	Space        string // int or stage or prod or...
	PiazzaSystem string // System-level username
	// contains filtered or unexported fields
}

func NewSystemConfig

func NewSystemConfig(serviceName ServiceName,
	requiredServices []ServiceName) (*SystemConfig, error)

func (*SystemConfig) AddService

func (sys *SystemConfig) AddService(name ServiceName, address string)

it is explicitly allowed for outsiders to update an existing service, but we'll log it just to be safe

func (*SystemConfig) GetAddress

func (sys *SystemConfig) GetAddress(name ServiceName) (string, error)

func (*SystemConfig) GetDomain

func (sys *SystemConfig) GetDomain() string

func (*SystemConfig) GetURL

func (sys *SystemConfig) GetURL(name ServiceName) (string, error)

func (*SystemConfig) WaitForService

func (sys *SystemConfig) WaitForService(name ServiceName) error

func (*SystemConfig) WaitForServiceToDie

func (sys *SystemConfig) WaitForServiceToDie(name ServiceName) error

type TimeStamp

type TimeStamp time.Time

TimeStamp is used for the timeStamp field of a syslog.Message, but it is here in pz-gocommon because it may be generally useful.

A Piazza timestamp must always be in RFC3339 format and in UTC. That is, we use yyyy-MM-dd'T'HH:mm:ss.SSSZ, with three caveats: (1) the ".SSS" (fractional seconds) part is optional (2) if the fractional part is present, there may actually be 1-7 digits used (3) however, if the fractional part is present when reading in or writing out, then the system may silently truncate or round to only three digits (milliseconds).

There are three basic operations: Now, Parse, and String. In these functions, note how we always are careful to round the time to milliseconds and then convert it to UTC before proceeding with any usages of Time objects or time strings.

Note that when Go marshals a Time object into JSON, it uses the "RFC3339Nano" format which may have several fractional digits. Note also that when storing a time object into Elasticsearch, the entire fractional part may be truncated to zero fractional digits (second accuracy) or three fractional digits (millisecond accuracy).

func NewTimeStamp

func NewTimeStamp() TimeStamp

func ParseTimeStamp

func ParseTimeStamp(s string) (TimeStamp, error)

func (TimeStamp) MarshalJSON

func (ts TimeStamp) MarshalJSON() ([]byte, error)

func (TimeStamp) String

func (ts TimeStamp) String() string

func (*TimeStamp) UnmarshalJSON

func (ts *TimeStamp) UnmarshalJSON(data []byte) error

func (*TimeStamp) Validate

func (ts *TimeStamp) Validate() error

type Uuid

type Uuid []byte

func NewUuid

func NewUuid() Uuid

NewRandom returns a random (variant 4) UUID.

func (Uuid) String

func (uuid Uuid) String() string

String returns the string form of uuid: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

func (Uuid) Valid

func (uuid Uuid) Valid() bool

type VcapApplication

type VcapApplication struct {
	ApplicationID      string         `json:"application_id"`
	ApplicationName    string         `json:"application_name"`
	ApplicationURIs    []string       `json:"application_uris"`
	ApplicationVersion string         `json:"application_version"`
	Limits             map[string]int `json:"limits"`
	Name               string         `json:"name"`
	SpaceId            string         `json:"space_id"`
	SpaceName          string         `json:"space_name"`
	URIs               []string       `json:"uris"`
	Users              interface{}    `json:"users"` // don't know what the datattype actually is
	Version            string         `json:"version"`
	// contains filtered or unexported fields
}

func NewVcapApplication

func NewVcapApplication(serviceName ServiceName) (*VcapApplication, error)

func (*VcapApplication) GetAddress

func (vcap *VcapApplication) GetAddress() string

func (*VcapApplication) GetBindToPort

func (vcap *VcapApplication) GetBindToPort() string

func (*VcapApplication) GetDomain

func (vcap *VcapApplication) GetDomain() string

func (*VcapApplication) GetName

func (vcap *VcapApplication) GetName() ServiceName

type VcapCredentials

type VcapCredentials struct {
	Host string `json:"host"`
}

type VcapServiceEntry

type VcapServiceEntry struct {
	Credentials    VcapCredentials `json:"credentials"`
	Label          string          `json:"label"`
	Name           string          `json:"name"`
	SyslogDrainUrl string          `json:"syslog_drain_url"`
	Tags           []string        `json:"tags"`
}

type VcapServices

type VcapServices struct {
	UserProvided []VcapServiceEntry `json:"user-provided"`

	Services map[ServiceName]string
}

func NewVcapServices

func NewVcapServices() (*VcapServices, error)

type Version

type Version struct {
	Version string
}

Version captures the information about the version of a service. For now, it is just a string.

Jump to

Keyboard shortcuts

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