From 285c1f162e19d9dd718e55dfde192ec285444a55 Mon Sep 17 00:00:00 2001 From: Ken Perkins Date: Tue, 10 Sep 2019 06:13:50 -0700 Subject: [PATCH 01/72] connector/saml: Adding group filtering - 4 new tests - Doc changes to use the group filtering --- Documentation/connectors/saml.md | 8 +++ connector/saml/saml.go | 59 ++++++++++++----- connector/saml/saml_test.go | 110 ++++++++++++++++++++++++++++--- 3 files changed, 150 insertions(+), 27 deletions(-) diff --git a/Documentation/connectors/saml.md b/Documentation/connectors/saml.md index 62cf6a7f..c9af0995 100644 --- a/Documentation/connectors/saml.md +++ b/Documentation/connectors/saml.md @@ -14,6 +14,10 @@ __The connector doesn't support refresh tokens__ since the SAML 2.0 protocol doe The connector doesn't support signed AuthnRequests or encrypted attributes. +## Group Filtering + +The SAML Connector supports providing a whitelist of SAML Groups to filter access based on, and when the `groupsattr` is set with a scope including groups, Dex will check for membership based on configured groups in the `allowedGroups` config setting for the SAML connector. + ## Configuration ```yaml @@ -44,6 +48,10 @@ connectors: emailAttr: email groupsAttr: groups # optional + # List of groups to filter access based on membership + # allowedGroups + # - Admins + # CA's can also be provided inline as a base64'd blob. # # caData: ( RAW base64'd PEM encoded CA ) diff --git a/connector/saml/saml.go b/connector/saml/saml.go index 4dac2aca..09414ea3 100644 --- a/connector/saml/saml.go +++ b/connector/saml/saml.go @@ -15,6 +15,7 @@ import ( "github.com/beevik/etree" "github.com/dexidp/dex/connector" + "github.com/dexidp/dex/pkg/groups" "github.com/dexidp/dex/pkg/log" dsig "github.com/russellhaering/goxmldsig" "github.com/russellhaering/goxmldsig/etreeutils" @@ -97,9 +98,9 @@ type Config struct { // If GroupsDelim is supplied the connector assumes groups are returned as a // single string instead of multiple attribute values. This delimiter will be // used split the groups string. - GroupsDelim string `json:"groupsDelim"` - - RedirectURI string `json:"redirectURI"` + GroupsDelim string `json:"groupsDelim"` + AllowedGroups []string `json:"allowedGroups"` + RedirectURI string `json:"redirectURI"` // Requested format of the NameID. The NameID value is is mapped to the ID Token // 'sub' claim. @@ -154,16 +155,17 @@ func (c *Config) openConnector(logger log.Logger) (*provider, error) { } p := &provider{ - entityIssuer: c.EntityIssuer, - ssoIssuer: c.SSOIssuer, - ssoURL: c.SSOURL, - now: time.Now, - usernameAttr: c.UsernameAttr, - emailAttr: c.EmailAttr, - groupsAttr: c.GroupsAttr, - groupsDelim: c.GroupsDelim, - redirectURI: c.RedirectURI, - logger: logger, + entityIssuer: c.EntityIssuer, + ssoIssuer: c.SSOIssuer, + ssoURL: c.SSOURL, + now: time.Now, + usernameAttr: c.UsernameAttr, + emailAttr: c.EmailAttr, + groupsAttr: c.GroupsAttr, + groupsDelim: c.GroupsDelim, + allowedGroups: c.AllowedGroups, + redirectURI: c.RedirectURI, + logger: logger, nameIDPolicyFormat: c.NameIDPolicyFormat, } @@ -232,10 +234,11 @@ type provider struct { validator *dsig.ValidationContext // Attribute mappings - usernameAttr string - emailAttr string - groupsAttr string - groupsDelim string + usernameAttr string + emailAttr string + groupsAttr string + groupsDelim string + allowedGroups []string redirectURI string @@ -388,11 +391,16 @@ func (p *provider) HandlePOST(s connector.Scopes, samlResponse, inResponseTo str return ident, fmt.Errorf("no attribute with name %q: %s", p.usernameAttr, attributes.names()) } - if !s.Groups || p.groupsAttr == "" { + if len(p.allowedGroups) == 0 && (!s.Groups || p.groupsAttr == "") { // Groups not requested or not configured. We're done. return ident, nil } + if len(p.allowedGroups) > 0 && (!s.Groups || p.groupsAttr == "") { + // allowedGroups set but no groups or groupsAttr. Disallowing. + return ident, fmt.Errorf("User not a member of allowed groups") + } + // Grab the groups. if p.groupsDelim != "" { groupsStr, ok := attributes.get(p.groupsAttr) @@ -408,6 +416,21 @@ func (p *provider) HandlePOST(s connector.Scopes, samlResponse, inResponseTo str } ident.Groups = groups } + + if len(p.allowedGroups) == 0 { + // No allowed groups set, just return the ident + return ident, nil + } + + // Look for membership in one of the allowed groups + groupMatches := groups.Filter(ident.Groups, p.allowedGroups) + + if len(groupMatches) == 0 { + // No group membership matches found, disallowing + return ident, fmt.Errorf("User not a member of allowed groups") + } + + // Otherwise, we're good return ident, nil } diff --git a/connector/saml/saml_test.go b/connector/saml/saml_test.go index d9aaf3f4..4d28e33a 100644 --- a/connector/saml/saml_test.go +++ b/connector/saml/saml_test.go @@ -49,9 +49,10 @@ type responseTest struct { entityIssuer string // Attribute customization. - usernameAttr string - emailAttr string - groupsAttr string + usernameAttr string + emailAttr string + groupsAttr string + allowedGroups []string // Expected outcome of the test. wantErr bool @@ -98,6 +99,96 @@ func TestGroups(t *testing.T) { test.run(t) } +func TestGroupsWhitelist(t *testing.T) { + test := responseTest{ + caFile: "testdata/ca.crt", + respFile: "testdata/good-resp.xml", + now: "2017-04-04T04:34:59.330Z", + usernameAttr: "Name", + emailAttr: "email", + groupsAttr: "groups", + allowedGroups: []string{"Admins"}, + inResponseTo: "6zmm5mguyebwvajyf2sdwwcw6m", + redirectURI: "http://127.0.0.1:5556/dex/callback", + wantIdent: connector.Identity{ + UserID: "eric.chiang+okta@coreos.com", + Username: "Eric", + Email: "eric.chiang+okta@coreos.com", + EmailVerified: true, + Groups: []string{"Admins", "Everyone"}, + }, + } + test.run(t) +} + +func TestGroupsWhitelistEmpty(t *testing.T) { + test := responseTest{ + caFile: "testdata/ca.crt", + respFile: "testdata/good-resp.xml", + now: "2017-04-04T04:34:59.330Z", + usernameAttr: "Name", + emailAttr: "email", + groupsAttr: "groups", + allowedGroups: []string{}, + inResponseTo: "6zmm5mguyebwvajyf2sdwwcw6m", + redirectURI: "http://127.0.0.1:5556/dex/callback", + wantIdent: connector.Identity{ + UserID: "eric.chiang+okta@coreos.com", + Username: "Eric", + Email: "eric.chiang+okta@coreos.com", + EmailVerified: true, + Groups: []string{"Admins", "Everyone"}, + }, + } + test.run(t) +} + +func TestGroupsWhitelistDisallowed(t *testing.T) { + test := responseTest{ + wantErr: true, + caFile: "testdata/ca.crt", + respFile: "testdata/good-resp.xml", + now: "2017-04-04T04:34:59.330Z", + usernameAttr: "Name", + emailAttr: "email", + groupsAttr: "groups", + allowedGroups: []string{"Nope"}, + inResponseTo: "6zmm5mguyebwvajyf2sdwwcw6m", + redirectURI: "http://127.0.0.1:5556/dex/callback", + wantIdent: connector.Identity{ + UserID: "eric.chiang+okta@coreos.com", + Username: "Eric", + Email: "eric.chiang+okta@coreos.com", + EmailVerified: true, + Groups: []string{"Admins", "Everyone"}, + }, + } + test.run(t) +} + +func TestGroupsWhitelistDisallowedNoGroupsOnIdent(t *testing.T) { + test := responseTest{ + wantErr: true, + caFile: "testdata/ca.crt", + respFile: "testdata/good-resp.xml", + now: "2017-04-04T04:34:59.330Z", + usernameAttr: "Name", + emailAttr: "email", + groupsAttr: "groups", + allowedGroups: []string{"Nope"}, + inResponseTo: "6zmm5mguyebwvajyf2sdwwcw6m", + redirectURI: "http://127.0.0.1:5556/dex/callback", + wantIdent: connector.Identity{ + UserID: "eric.chiang+okta@coreos.com", + Username: "Eric", + Email: "eric.chiang+okta@coreos.com", + EmailVerified: true, + Groups: []string{}, + }, + } + test.run(t) +} + // TestOkta tests against an actual response from Okta. func TestOkta(t *testing.T) { test := responseTest{ @@ -290,12 +381,13 @@ func loadCert(ca string) (*x509.Certificate, error) { func (r responseTest) run(t *testing.T) { c := Config{ - CA: r.caFile, - UsernameAttr: r.usernameAttr, - EmailAttr: r.emailAttr, - GroupsAttr: r.groupsAttr, - RedirectURI: r.redirectURI, - EntityIssuer: r.entityIssuer, + CA: r.caFile, + UsernameAttr: r.usernameAttr, + EmailAttr: r.emailAttr, + GroupsAttr: r.groupsAttr, + RedirectURI: r.redirectURI, + EntityIssuer: r.entityIssuer, + AllowedGroups: r.allowedGroups, // Never logging in, don't need this. SSOURL: "http://foo.bar/", } From 512cb3169ea0d9ca7207616d08426455820727c9 Mon Sep 17 00:00:00 2001 From: Thomas Jackson Date: Fri, 13 Sep 2019 11:10:44 -0700 Subject: [PATCH 02/72] Run getUserInfo prior to claim enforcement If you have an oidc connector configured *and* that IDP provides thin tokens (e.g. okta) then the majority of the requested claims come in the getUserInfo call (such as email_verified). So if getUserInfo is configured it should be run before claims are validated. --- connector/oidc/oidc.go | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/connector/oidc/oidc.go b/connector/oidc/oidc.go index 4a64df8b..b5e075ad 100644 --- a/connector/oidc/oidc.go +++ b/connector/oidc/oidc.go @@ -213,6 +213,17 @@ func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (ide return identity, fmt.Errorf("oidc: failed to decode claims: %v", err) } + // We immediately want to run getUserInfo if configured before we validate the claims + if c.getUserInfo { + userInfo, err := c.provider.UserInfo(r.Context(), oauth2.StaticTokenSource(token)) + if err != nil { + return identity, fmt.Errorf("oidc: error loading userinfo: %v", err) + } + if err := userInfo.Claims(&claims); err != nil { + return identity, fmt.Errorf("oidc: failed to decode userinfo claims: %v", err) + } + } + userNameKey := "name" if c.userNameKey != "" { userNameKey = c.userNameKey @@ -249,16 +260,6 @@ func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (ide } } - if c.getUserInfo { - userInfo, err := c.provider.UserInfo(r.Context(), oauth2.StaticTokenSource(token)) - if err != nil { - return identity, fmt.Errorf("oidc: error loading userinfo: %v", err) - } - if err := userInfo.Claims(&claims); err != nil { - return identity, fmt.Errorf("oidc: failed to decode userinfo claims: %v", err) - } - } - identity = connector.Identity{ UserID: idToken.Subject, Username: name, From 21ab30d20767283b4696c992644432a38fc23849 Mon Sep 17 00:00:00 2001 From: Thomas Jackson Date: Thu, 12 Sep 2019 16:12:29 -0700 Subject: [PATCH 03/72] Add option to enable groups for oidc connectors There's been some discussion in #1065 regarding what to do about refreshing groups. As it stands today dex doesn't update any of the claims on refresh (groups would just be another one). The main concern with enabling it is that group claims may change more frequently. While we continue to wait on the upstream refresh flows, this adds an option to enable the group claim. This is disabled by default (so no behavioral change) but enables those that are willing to have the delay in group claim change to use oidc IDPs. Workaround to #1065 --- Documentation/connectors/oidc.md | 7 +++++++ connector/oidc/oidc.go | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/Documentation/connectors/oidc.md b/Documentation/connectors/oidc.md index 55b7a96e..20eedd96 100644 --- a/Documentation/connectors/oidc.md +++ b/Documentation/connectors/oidc.md @@ -61,6 +61,13 @@ connectors: # This can be overridden with the below option # insecureSkipEmailVerified: true + # Groups claims (like the rest of oidc claims through dex) only refresh when the id token is refreshed + # meaning the regular refresh flow doesn't update the groups claim. As such by default the oidc connector + # doesn't allow groups claims. If you are okay with having potentially stale group claims you can use + # this option to enable groups claims through the oidc connector on a per-connector basis. + # This can be overridden with the below option + # insecureEnableGroups: true + # When enabled, the OpenID Connector will query the UserInfo endpoint for additional claims. UserInfo claims # take priority over claims returned by the IDToken. This option should be used when the IDToken doesn't contain # all the claims requested. diff --git a/connector/oidc/oidc.go b/connector/oidc/oidc.go index 4a64df8b..f638aa6e 100644 --- a/connector/oidc/oidc.go +++ b/connector/oidc/oidc.go @@ -40,6 +40,9 @@ type Config struct { // Override the value of email_verifed to true in the returned claims InsecureSkipEmailVerified bool `json:"insecureSkipEmailVerified"` + // InsecureEnableGroups enables groups claims. This is disabled by default until https://github.com/dexidp/dex/issues/1065 is resolved + InsecureEnableGroups bool `json:"insecureEnableGroups"` + // GetUserInfo uses the userinfo endpoint to get additional claims for // the token. This is especially useful where upstreams return "thin" // id tokens @@ -132,6 +135,7 @@ func (c *Config) Open(id string, logger log.Logger) (conn connector.Connector, e cancel: cancel, hostedDomains: c.HostedDomains, insecureSkipEmailVerified: c.InsecureSkipEmailVerified, + insecureEnableGroups: c.InsecureEnableGroups, getUserInfo: c.GetUserInfo, userIDKey: c.UserIDKey, userNameKey: c.UserNameKey, @@ -152,6 +156,7 @@ type oidcConnector struct { logger log.Logger hostedDomains []string insecureSkipEmailVerified bool + insecureEnableGroups bool getUserInfo bool userIDKey string userNameKey string @@ -274,6 +279,19 @@ func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (ide identity.UserID = userID } + if c.insecureEnableGroups { + vs, ok := claims["groups"].([]interface{}) + if ok { + for _, v := range vs { + if s, ok := v.(string); ok { + identity.Groups = append(identity.Groups, s) + } else { + return identity, errors.New("malformed \"groups\" claim") + } + } + } + } + return identity, nil } From d2c33db8a8ff688d2be91c2edf3cc99baca3dc8b Mon Sep 17 00:00:00 2001 From: Nandor Kracser Date: Mon, 23 Sep 2019 09:36:01 +0200 Subject: [PATCH 04/72] storage/mysql: support pre-5.7.20 instances with tx_isolation only --- storage/sql/config.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/storage/sql/config.go b/storage/sql/config.go index 0095b57d..24467169 100644 --- a/storage/sql/config.go +++ b/storage/sql/config.go @@ -29,6 +29,7 @@ const ( // MySQL error codes mysqlErrDupEntry = 1062 mysqlErrDupEntryWithKeyName = 1586 + mysqlErrUnknownSysVar = 1193 ) // SQLite3 options for creating an SQL db. @@ -307,6 +308,26 @@ func (s *MySQL) open(logger log.Logger) (*conn, error) { return nil, err } + err = db.Ping() + if err != nil { + if mysqlErr, ok := err.(*mysql.MySQLError); ok && mysqlErr.Number == mysqlErrUnknownSysVar { + logger.Info("reconnecting with MySQL pre-5.7.20 compatibilty mode") + + // MySQL 5.7.20 introduced transaction_isolation and deprecated tx_isolation. + // MySQL 8.0 doesn't have tx_isolation at all. + // https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_transaction_isolation + delete(cfg.Params, "transaction_isolation") + cfg.Params["tx_isolation"] = "'SERIALIZABLE'" + + db, err = sql.Open("mysql", cfg.FormatDSN()) + if err != nil { + return nil, err + } + } else { + return nil, err + } + } + errCheck := func(err error) bool { sqlErr, ok := err.(*mysql.MySQLError) if !ok { From 2c52c52686c928f3137b3cbffabb03145bb83914 Mon Sep 17 00:00:00 2001 From: "j.ai" Date: Fri, 27 Sep 2019 17:45:52 -0700 Subject: [PATCH 05/72] Fix URLs in curl cmd as stated in the overview doc. --- Documentation/openid-connect.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentation/openid-connect.md b/Documentation/openid-connect.md index 2d338b8c..1a90c88a 100644 --- a/Documentation/openid-connect.md +++ b/Documentation/openid-connect.md @@ -92,7 +92,7 @@ OpenID Connect servers have a discovery mechanism for OAuth2 endpoints, scopes supported, and indications of various other OpenID Connect features. ``` -$ curl http://127.0.0.1:5556/.well-known/openid-configuration +$ curl http://127.0.0.1:5556/dex/.well-known/openid-configuration { "issuer": "http://127.0.0.1:5556", "authorization_endpoint": "http://127.0.0.1:5556/auth", @@ -123,7 +123,7 @@ https://tools.ietf.org/html/rfc7517) Set of public keys that will look something like this: ``` -$ curl http://127.0.0.1:5556/keys +$ curl http://127.0.0.1:5556/dex/keys { "keys": [ { From 839130f01ce46d719351ad264a844d609978f116 Mon Sep 17 00:00:00 2001 From: Yannis Zarkadas Date: Fri, 27 Sep 2019 16:56:32 +0300 Subject: [PATCH 06/72] handlers: change all handlers to pass down http request Signed-off-by: Yannis Zarkadas --- server/handlers.go | 92 +++++++++++++++++++++++----------------------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/server/handlers.go b/server/handlers.go index 9bff36ee..1391e589 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -101,7 +101,7 @@ func (h *healthChecker) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.mu.RUnlock() if err != nil { - h.s.renderError(w, http.StatusInternalServerError, "Health check failed.") + h.s.renderError(r, w, http.StatusInternalServerError, "Health check failed.") return } fmt.Fprintf(w, "Health check passed in %s", t) @@ -112,13 +112,13 @@ func (s *Server) handlePublicKeys(w http.ResponseWriter, r *http.Request) { keys, err := s.storage.GetKeys() if err != nil { s.logger.Errorf("failed to get keys: %v", err) - s.renderError(w, http.StatusInternalServerError, "Internal server error.") + s.renderError(r, w, http.StatusInternalServerError, "Internal server error.") return } if keys.SigningKeyPub == nil { s.logger.Errorf("No public keys found.") - s.renderError(w, http.StatusInternalServerError, "Internal server error.") + s.renderError(r, w, http.StatusInternalServerError, "Internal server error.") return } @@ -133,7 +133,7 @@ func (s *Server) handlePublicKeys(w http.ResponseWriter, r *http.Request) { data, err := json.MarshalIndent(jwks, "", " ") if err != nil { s.logger.Errorf("failed to marshal discovery data: %v", err) - s.renderError(w, http.StatusInternalServerError, "Internal server error.") + s.renderError(r, w, http.StatusInternalServerError, "Internal server error.") return } maxAge := keys.NextRotation.Sub(s.now()) @@ -214,7 +214,7 @@ func (s *Server) handleAuthorization(w http.ResponseWriter, r *http.Request) { status = err.Status() } - s.renderError(w, status, err.Error()) + s.renderError(r, w, status, err.Error()) return } @@ -226,14 +226,14 @@ func (s *Server) handleAuthorization(w http.ResponseWriter, r *http.Request) { authReq.Expiry = s.now().Add(s.authRequestsValidFor) if err := s.storage.CreateAuthRequest(*authReq); err != nil { s.logger.Errorf("Failed to create authorization request: %v", err) - s.renderError(w, http.StatusInternalServerError, "Failed to connect to the database.") + s.renderError(r, w, http.StatusInternalServerError, "Failed to connect to the database.") return } connectors, err := s.storage.ListConnectors() if err != nil { s.logger.Errorf("Failed to get list of connectors: %v", err) - s.renderError(w, http.StatusInternalServerError, "Failed to retrieve connector list.") + s.renderError(r, w, http.StatusInternalServerError, "Failed to retrieve connector list.") return } @@ -271,7 +271,7 @@ func (s *Server) handleAuthorization(w http.ResponseWriter, r *http.Request) { i++ } - if err := s.templates.login(w, connectorInfos); err != nil { + if err := s.templates.login(r, w, connectorInfos, r.URL.Path); err != nil { s.logger.Errorf("Server template error: %v", err) } } @@ -281,7 +281,7 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) { conn, err := s.getConnector(connID) if err != nil { s.logger.Errorf("Failed to create authorization request: %v", err) - s.renderError(w, http.StatusBadRequest, "Requested resource does not exist") + s.renderError(r, w, http.StatusBadRequest, "Requested resource does not exist") return } @@ -291,9 +291,9 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) { if err != nil { s.logger.Errorf("Failed to get auth request: %v", err) if err == storage.ErrNotFound { - s.renderError(w, http.StatusBadRequest, "Login session expired.") + s.renderError(r, w, http.StatusBadRequest, "Login session expired.") } else { - s.renderError(w, http.StatusInternalServerError, "Database error.") + s.renderError(r, w, http.StatusInternalServerError, "Database error.") } return } @@ -306,7 +306,7 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) { } if err := s.storage.UpdateAuthRequest(authReqID, updater); err != nil { s.logger.Errorf("Failed to set connector ID on auth request: %v", err) - s.renderError(w, http.StatusInternalServerError, "Database error.") + s.renderError(r, w, http.StatusInternalServerError, "Database error.") return } } @@ -324,19 +324,19 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) { callbackURL, err := conn.LoginURL(scopes, s.absURL("/callback"), authReqID) if err != nil { s.logger.Errorf("Connector %q returned error when creating callback: %v", connID, err) - s.renderError(w, http.StatusInternalServerError, "Login error.") + s.renderError(r, w, http.StatusInternalServerError, "Login error.") return } http.Redirect(w, r, callbackURL, http.StatusFound) case connector.PasswordConnector: - if err := s.templates.password(w, r.URL.String(), "", usernamePrompt(conn), false, showBacklink); err != nil { + if err := s.templates.password(r, w, r.URL.String(), "", usernamePrompt(conn), false, showBacklink, r.URL.Path); err != nil { s.logger.Errorf("Server template error: %v", err) } case connector.SAMLConnector: action, value, err := conn.POSTData(scopes, authReqID) if err != nil { s.logger.Errorf("Creating SAML data: %v", err) - s.renderError(w, http.StatusInternalServerError, "Connector Login Error") + s.renderError(r, w, http.StatusInternalServerError, "Connector Login Error") return } @@ -358,12 +358,12 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) { `, action, value, authReqID) default: - s.renderError(w, http.StatusBadRequest, "Requested resource does not exist.") + s.renderError(r, w, http.StatusBadRequest, "Requested resource does not exist.") } case http.MethodPost: passwordConnector, ok := conn.Connector.(connector.PasswordConnector) if !ok { - s.renderError(w, http.StatusBadRequest, "Requested resource does not exist.") + s.renderError(r, w, http.StatusBadRequest, "Requested resource does not exist.") return } @@ -373,11 +373,11 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) { identity, ok, err := passwordConnector.Login(r.Context(), scopes, username, password) if err != nil { s.logger.Errorf("Failed to login user: %v", err) - s.renderError(w, http.StatusInternalServerError, fmt.Sprintf("Login error: %v", err)) + s.renderError(r, w, http.StatusInternalServerError, fmt.Sprintf("Login error: %v", err)) return } if !ok { - if err := s.templates.password(w, r.URL.String(), username, usernamePrompt(passwordConnector), true, showBacklink); err != nil { + if err := s.templates.password(r, w, r.URL.String(), username, usernamePrompt(passwordConnector), true, showBacklink, r.URL.Path); err != nil { s.logger.Errorf("Server template error: %v", err) } return @@ -385,13 +385,13 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) { redirectURL, err := s.finalizeLogin(identity, authReq, conn.Connector) if err != nil { s.logger.Errorf("Failed to finalize login: %v", err) - s.renderError(w, http.StatusInternalServerError, "Login error.") + s.renderError(r, w, http.StatusInternalServerError, "Login error.") return } http.Redirect(w, r, redirectURL, http.StatusSeeOther) default: - s.renderError(w, http.StatusBadRequest, "Unsupported request method.") + s.renderError(r, w, http.StatusBadRequest, "Unsupported request method.") } } @@ -400,16 +400,16 @@ func (s *Server) handleConnectorCallback(w http.ResponseWriter, r *http.Request) switch r.Method { case http.MethodGet: // OAuth2 callback if authID = r.URL.Query().Get("state"); authID == "" { - s.renderError(w, http.StatusBadRequest, "User session error.") + s.renderError(r, w, http.StatusBadRequest, "User session error.") return } case http.MethodPost: // SAML POST binding if authID = r.PostFormValue("RelayState"); authID == "" { - s.renderError(w, http.StatusBadRequest, "User session error.") + s.renderError(r, w, http.StatusBadRequest, "User session error.") return } default: - s.renderError(w, http.StatusBadRequest, "Method not supported") + s.renderError(r, w, http.StatusBadRequest, "Method not supported") return } @@ -417,24 +417,24 @@ func (s *Server) handleConnectorCallback(w http.ResponseWriter, r *http.Request) if err != nil { if err == storage.ErrNotFound { s.logger.Errorf("Invalid 'state' parameter provided: %v", err) - s.renderError(w, http.StatusBadRequest, "Requested resource does not exist.") + s.renderError(r, w, http.StatusBadRequest, "Requested resource does not exist.") return } s.logger.Errorf("Failed to get auth request: %v", err) - s.renderError(w, http.StatusInternalServerError, "Database error.") + s.renderError(r, w, http.StatusInternalServerError, "Database error.") return } if connID := mux.Vars(r)["connector"]; connID != "" && connID != authReq.ConnectorID { s.logger.Errorf("Connector mismatch: authentication started with id %q, but callback for id %q was triggered", authReq.ConnectorID, connID) - s.renderError(w, http.StatusInternalServerError, "Requested resource does not exist.") + s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") return } conn, err := s.getConnector(authReq.ConnectorID) if err != nil { s.logger.Errorf("Failed to get connector with id %q : %v", authReq.ConnectorID, err) - s.renderError(w, http.StatusInternalServerError, "Requested resource does not exist.") + s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") return } @@ -443,32 +443,32 @@ func (s *Server) handleConnectorCallback(w http.ResponseWriter, r *http.Request) case connector.CallbackConnector: if r.Method != http.MethodGet { s.logger.Errorf("SAML request mapped to OAuth2 connector") - s.renderError(w, http.StatusBadRequest, "Invalid request") + s.renderError(r, w, http.StatusBadRequest, "Invalid request") return } identity, err = conn.HandleCallback(parseScopes(authReq.Scopes), r) case connector.SAMLConnector: if r.Method != http.MethodPost { s.logger.Errorf("OAuth2 request mapped to SAML connector") - s.renderError(w, http.StatusBadRequest, "Invalid request") + s.renderError(r, w, http.StatusBadRequest, "Invalid request") return } identity, err = conn.HandlePOST(parseScopes(authReq.Scopes), r.PostFormValue("SAMLResponse"), authReq.ID) default: - s.renderError(w, http.StatusInternalServerError, "Requested resource does not exist.") + s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") return } if err != nil { s.logger.Errorf("Failed to authenticate: %v", err) - s.renderError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to authenticate: %v", err)) + s.renderError(r, w, http.StatusInternalServerError, fmt.Sprintf("Failed to authenticate: %v", err)) return } redirectURL, err := s.finalizeLogin(identity, authReq, conn.Connector) if err != nil { s.logger.Errorf("Failed to finalize login: %v", err) - s.renderError(w, http.StatusInternalServerError, "Login error.") + s.renderError(r, w, http.StatusInternalServerError, "Login error.") return } @@ -511,12 +511,12 @@ func (s *Server) handleApproval(w http.ResponseWriter, r *http.Request) { authReq, err := s.storage.GetAuthRequest(r.FormValue("req")) if err != nil { s.logger.Errorf("Failed to get auth request: %v", err) - s.renderError(w, http.StatusInternalServerError, "Database error.") + s.renderError(r, w, http.StatusInternalServerError, "Database error.") return } if !authReq.LoggedIn { s.logger.Errorf("Auth request does not have an identity for approval") - s.renderError(w, http.StatusInternalServerError, "Login process not yet finalized.") + s.renderError(r, w, http.StatusInternalServerError, "Login process not yet finalized.") return } @@ -529,15 +529,15 @@ func (s *Server) handleApproval(w http.ResponseWriter, r *http.Request) { client, err := s.storage.GetClient(authReq.ClientID) if err != nil { s.logger.Errorf("Failed to get client %q: %v", authReq.ClientID, err) - s.renderError(w, http.StatusInternalServerError, "Failed to retrieve client.") + s.renderError(r, w, http.StatusInternalServerError, "Failed to retrieve client.") return } - if err := s.templates.approval(w, authReq.ID, authReq.Claims.Username, client.Name, authReq.Scopes); err != nil { + if err := s.templates.approval(r, w, authReq.ID, authReq.Claims.Username, client.Name, authReq.Scopes, r.URL.Path); err != nil { s.logger.Errorf("Server template error: %v", err) } case http.MethodPost: if r.FormValue("approval") != "approve" { - s.renderError(w, http.StatusInternalServerError, "Approval rejected.") + s.renderError(r, w, http.StatusInternalServerError, "Approval rejected.") return } s.sendCodeResponse(w, r, authReq) @@ -546,22 +546,22 @@ func (s *Server) handleApproval(w http.ResponseWriter, r *http.Request) { func (s *Server) sendCodeResponse(w http.ResponseWriter, r *http.Request, authReq storage.AuthRequest) { if s.now().After(authReq.Expiry) { - s.renderError(w, http.StatusBadRequest, "User session has expired.") + s.renderError(r, w, http.StatusBadRequest, "User session has expired.") return } if err := s.storage.DeleteAuthRequest(authReq.ID); err != nil { if err != storage.ErrNotFound { s.logger.Errorf("Failed to delete authorization request: %v", err) - s.renderError(w, http.StatusInternalServerError, "Internal server error.") + s.renderError(r, w, http.StatusInternalServerError, "Internal server error.") } else { - s.renderError(w, http.StatusBadRequest, "User session error.") + s.renderError(r, w, http.StatusBadRequest, "User session error.") } return } u, err := url.Parse(authReq.RedirectURI) if err != nil { - s.renderError(w, http.StatusInternalServerError, "Invalid redirect URI.") + s.renderError(r, w, http.StatusInternalServerError, "Invalid redirect URI.") return } @@ -598,14 +598,14 @@ func (s *Server) sendCodeResponse(w http.ResponseWriter, r *http.Request, authRe } if err := s.storage.CreateAuthCode(code); err != nil { s.logger.Errorf("Failed to create auth code: %v", err) - s.renderError(w, http.StatusInternalServerError, "Internal server error.") + s.renderError(r, w, http.StatusInternalServerError, "Internal server error.") return } // Implicit and hybrid flows that try to use the OOB redirect URI are // rejected earlier. If we got here we're using the code flow. if authReq.RedirectURI == redirectURIOOB { - if err := s.templates.oob(w, code.ID); err != nil { + if err := s.templates.oob(r, w, code.ID, r.URL.Path); err != nil { s.logger.Errorf("Server template error: %v", err) } return @@ -1119,8 +1119,8 @@ func (s *Server) writeAccessToken(w http.ResponseWriter, idToken, accessToken, r w.Write(data) } -func (s *Server) renderError(w http.ResponseWriter, status int, description string) { - if err := s.templates.err(w, status, description); err != nil { +func (s *Server) renderError(r *http.Request, w http.ResponseWriter, status int, description string) { + if err := s.templates.err(r, w, status, description); err != nil { s.logger.Errorf("Server template error: %v", err) } } From 27944d4f8f1f646d034c8e1cd7a8357d6e060933 Mon Sep 17 00:00:00 2001 From: Yannis Zarkadas Date: Fri, 27 Sep 2019 17:04:43 +0300 Subject: [PATCH 07/72] templates: add new relativeURL function Signed-off-by: Yannis Zarkadas --- server/templates.go | 101 ++++++++++++++++++++++++++++++++++----- server/templates_test.go | 43 +++++++++++++++++ 2 files changed, 131 insertions(+), 13 deletions(-) diff --git a/server/templates.go b/server/templates.go index 89d41371..88aeace0 100644 --- a/server/templates.go +++ b/server/templates.go @@ -6,7 +6,9 @@ import ( "io" "io/ioutil" "net/http" + "net/url" "os" + "path" "path/filepath" "sort" "strings" @@ -94,7 +96,7 @@ func loadWebConfig(c webConfig) (static, theme http.Handler, templates *template c.dir = "./web" } if c.logoURL == "" { - c.logoURL = join(c.issuerURL, "theme/logo.png") + c.logoURL = "theme/logo.png" } if err := dirExists(c.dir); err != nil { @@ -136,10 +138,15 @@ func loadTemplates(c webConfig, templatesDir string) (*templates, error) { return nil, fmt.Errorf("no files in template dir %q", templatesDir) } + issuerURL, err := url.Parse(c.issuerURL) + if err != nil { + return nil, fmt.Errorf("error parsing issuerURL: %v", err) + } + funcs := map[string]interface{}{ "issuer": func() string { return c.issuer }, "logo": func() string { return c.logoURL }, - "url": func(s string) string { return join(c.issuerURL, s) }, + "url": func(reqPath, assetPath string) string { return relativeURL(issuerURL.Path, reqPath, assetPath) }, "lower": strings.ToLower, "extra": func(k string) string { return c.extra[k] }, } @@ -166,6 +173,69 @@ func loadTemplates(c webConfig, templatesDir string) (*templates, error) { }, nil } +// relativeURL returns the URL of the asset relative to the URL of the request path. +// The serverPath is consulted to trim any prefix due in case it is not listening +// to the root path. +// +// Algorithm: +// 1. Remove common prefix of serverPath and reqPath +// 2. Remove common prefix of assetPath and reqPath +// 3. For each part of reqPath remaining(minus one), go up one level (..) +// 4. For each part of assetPath remaining, append it to result +// +//eg +//server listens at localhost/dex so serverPath is dex +//reqPath is /dex/auth +//assetPath is static/main.css +//relativeURL("/dex", "/dex/auth", "static/main.css") = "../static/main.css" +func relativeURL(serverPath, reqPath, assetPath string) string { + + splitPath := func(p string) []string { + res := []string{} + parts := strings.Split(path.Clean(p), "/") + for _, part := range parts { + if part != "" { + res = append(res, part) + } + } + return res + } + + stripCommonParts := func(s1, s2 []string) ([]string, []string) { + min := len(s1) + if len(s2) < min { + min = len(s2) + } + + splitIndex := min + for i := 0; i < min; i++ { + if s1[i] != s2[i] { + splitIndex = i + break + } + } + return s1[splitIndex:], s2[splitIndex:] + } + + server, req, asset := splitPath(serverPath), splitPath(reqPath), splitPath(assetPath) + + // Remove common prefix of request path with server path + server, req = stripCommonParts(server, req) + + // Remove common prefix of request path with asset path + asset, req = stripCommonParts(asset, req) + + // For each part of the request remaining (minus one) -> go up one level (..) + // For each part of the asset remaining -> append it + var relativeURL string + for i := 0; i < len(req)-1; i++ { + relativeURL = path.Join("..", relativeURL) + } + relativeURL = path.Join(relativeURL, path.Join(asset...)) + + return relativeURL +} + var scopeDescriptions = map[string]string{ "offline_access": "Have offline access", "profile": "View basic profile information", @@ -184,26 +254,28 @@ func (n byName) Len() int { return len(n) } func (n byName) Less(i, j int) bool { return n[i].Name < n[j].Name } func (n byName) Swap(i, j int) { n[i], n[j] = n[j], n[i] } -func (t *templates) login(w http.ResponseWriter, connectors []connectorInfo) error { +func (t *templates) login(r *http.Request, w http.ResponseWriter, connectors []connectorInfo, reqPath string) error { sort.Sort(byName(connectors)) data := struct { Connectors []connectorInfo - }{connectors} + ReqPath string + }{connectors, r.URL.Path} return renderTemplate(w, t.loginTmpl, data) } -func (t *templates) password(w http.ResponseWriter, postURL, lastUsername, usernamePrompt string, lastWasInvalid, showBacklink bool) error { +func (t *templates) password(r *http.Request, w http.ResponseWriter, postURL, lastUsername, usernamePrompt string, lastWasInvalid, showBacklink bool, reqPath string) error { data := struct { PostURL string BackLink bool Username string UsernamePrompt string Invalid bool - }{postURL, showBacklink, lastUsername, usernamePrompt, lastWasInvalid} + ReqPath string + }{postURL, showBacklink, lastUsername, usernamePrompt, lastWasInvalid, r.URL.Path} return renderTemplate(w, t.passwordTmpl, data) } -func (t *templates) approval(w http.ResponseWriter, authReqID, username, clientName string, scopes []string) error { +func (t *templates) approval(r *http.Request, w http.ResponseWriter, authReqID, username, clientName string, scopes []string, reqPath string) error { accesses := []string{} for _, scope := range scopes { access, ok := scopeDescriptions[scope] @@ -217,23 +289,26 @@ func (t *templates) approval(w http.ResponseWriter, authReqID, username, clientN Client string AuthReqID string Scopes []string - }{username, clientName, authReqID, accesses} + ReqPath string + }{username, clientName, authReqID, accesses, r.URL.Path} return renderTemplate(w, t.approvalTmpl, data) } -func (t *templates) oob(w http.ResponseWriter, code string) error { +func (t *templates) oob(r *http.Request, w http.ResponseWriter, code string, reqPath string) error { data := struct { - Code string - }{code} + Code string + ReqPath string + }{code, r.URL.Path} return renderTemplate(w, t.oobTmpl, data) } -func (t *templates) err(w http.ResponseWriter, errCode int, errMsg string) error { +func (t *templates) err(r *http.Request, w http.ResponseWriter, errCode int, errMsg string) error { w.WriteHeader(errCode) data := struct { ErrType string ErrMsg string - }{http.StatusText(errCode), errMsg} + ReqPath string + }{http.StatusText(errCode), errMsg, r.URL.Path} if err := t.errorTmpl.Execute(w, data); err != nil { return fmt.Errorf("Error rendering template %s: %s", t.errorTmpl.Name(), err) } diff --git a/server/templates_test.go b/server/templates_test.go index abb4e431..5ead66e5 100644 --- a/server/templates_test.go +++ b/server/templates_test.go @@ -1 +1,44 @@ package server + +import "testing" + +func TestRelativeURL(t *testing.T) { + tests := []struct { + name string + serverPath string + reqPath string + assetPath string + expected string + }{ + { + name: "server-root-req-one-level-asset-two-level", + serverPath: "/", + reqPath: "/auth", + assetPath: "/theme/main.css", + expected: "theme/main.css", + }, + { + name: "server-one-level-req-one-level-asset-two-level", + serverPath: "/dex", + reqPath: "/dex/auth", + assetPath: "/theme/main.css", + expected: "theme/main.css", + }, + { + name: "server-root-req-two-level-asset-three-level", + serverPath: "/dex", + reqPath: "/dex/auth/connector", + assetPath: "assets/css/main.css", + expected: "../assets/css/main.css", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + actual := relativeURL(test.serverPath, test.reqPath, test.assetPath) + if actual != test.expected { + t.Fatalf("Got '%s'. Expected '%s'", actual, test.expected) + } + }) + } +} From 59beb7425f8d380e59b7ab0365d8d4b8fe47c511 Mon Sep 17 00:00:00 2001 From: Yannis Zarkadas Date: Fri, 27 Sep 2019 17:04:55 +0300 Subject: [PATCH 08/72] web: change header template to use new url function Signed-off-by: Yannis Zarkadas --- web/templates/header.html | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/web/templates/header.html b/web/templates/header.html index edd6289a..0d4fea0f 100644 --- a/web/templates/header.html +++ b/web/templates/header.html @@ -5,15 +5,15 @@ {{ issuer }} - - - + + +
- +
From 69d13b766df415141b49eb86395da03105ebcd5d Mon Sep 17 00:00:00 2001 From: Yannis Zarkadas Date: Fri, 27 Sep 2019 17:23:38 +0300 Subject: [PATCH 09/72] gitignore: add .idea folder Signed-off-by: Yannis Zarkadas --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index db3eaf3e..21ad3ba8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ bin dist _output +.idea From 76c76a0b3910bc2d9ba195bbe511a6d229d93f9f Mon Sep 17 00:00:00 2001 From: Ta-Ching Chen Date: Sun, 13 Oct 2019 15:24:22 +0800 Subject: [PATCH 10/72] Add note for redirect uri --- Documentation/kubernetes.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Documentation/kubernetes.md b/Documentation/kubernetes.md index 80edf2e4..b7874c90 100644 --- a/Documentation/kubernetes.md +++ b/Documentation/kubernetes.md @@ -156,6 +156,9 @@ Once the example app is running, choose the GitHub option and grant access to de The default redirect uri is http://127.0.0.1:5555/callback and can be changed with the `--redirect-uri` flag and should correspond with your configmap. +Please note the redirect uri is different from the one you filled when creating `GitHub OAuth2 client credentials`. +When you login, GitHub first redirects to dex (https://dex.example.com:32000/callback), then dex redirects to the redirect uri of exampl-app. + The printed ID Token can then be used as a bearer token to authenticate against the API server. ``` From 6e35f243995911b2d095987734b6a6b3a6ddb87b Mon Sep 17 00:00:00 2001 From: Tony Hsu Date: Tue, 22 Oct 2019 11:27:12 +0800 Subject: [PATCH 11/72] Fix typo --- Documentation/connectors/ldap.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/connectors/ldap.md b/Documentation/connectors/ldap.md index 20f0e406..626cd650 100644 --- a/Documentation/connectors/ldap.md +++ b/Documentation/connectors/ldap.md @@ -13,7 +13,7 @@ The connector executes two primary queries: The dex repo contains a basic LDAP setup using [OpenLDAP][openldap]. -First start the LDAP server using the example script. This will run the OpenLDAP daemon and seed it with a initial set of users. +First start the LDAP server using the example script. This will run the OpenLDAP daemon and seed it with an initial set of users. ``` ./scripts/slapd.sh From c1b421fa0460c5aca9c23c7b56501b64d577f5cc Mon Sep 17 00:00:00 2001 From: Nandor Kracser Date: Thu, 10 Oct 2019 16:43:41 +0200 Subject: [PATCH 12/72] add preffered_username to idToken Signed-off-by: Nandor Kracser --- README.md | 22 +++++----- connector/connector.go | 9 ++-- connector/github/github.go | 10 +++-- connector/gitlab/gitlab.go | 10 +++-- connector/ldap/ldap.go | 18 ++++++-- server/handlers.go | 26 ++++++----- server/oauth2.go | 4 +- storage/etcd/types.go | 33 +++++++------- storage/kubernetes/types.go | 33 +++++++------- storage/sql/crud.go | 87 ++++++++++++++++++++----------------- storage/sql/migrate.go | 12 +++++ storage/storage.go | 9 ++-- 12 files changed, 160 insertions(+), 113 deletions(-) diff --git a/README.md b/README.md index 9161dad1..7247270a 100644 --- a/README.md +++ b/README.md @@ -63,17 +63,17 @@ Depending on the connectors limitations in protocols can prevent dex from issuin Dex implements the following connectors: -| Name | supports refresh tokens | supports groups claim | status | notes | -| ---- | ----------------------- | --------------------- | ------ | ----- | -| [LDAP](Documentation/connectors/ldap.md) | yes | yes | stable | | -| [GitHub](Documentation/connectors/github.md) | yes | yes | stable | | -| [SAML 2.0](Documentation/connectors/saml.md) | no | yes | stable | -| [GitLab](Documentation/connectors/gitlab.md) | yes | yes | beta | | -| [OpenID Connect](Documentation/connectors/oidc.md) | yes | no ([#1065][issue-1065]) | beta | Includes Google, Salesforce, Azure, etc. | -| [LinkedIn](Documentation/connectors/linkedin.md) | yes | no | beta | | -| [Microsoft](Documentation/connectors/microsoft.md) | yes | yes | beta | | -| [AuthProxy](Documentation/connectors/authproxy.md) | no | no | alpha | Authentication proxies such as Apache2 mod_auth, etc. | -| [Bitbucket Cloud](Documentation/connectors/bitbucketcloud.md) | yes | yes | alpha | | +| Name | supports refresh tokens | supports groups claim | supports preferred_username claim | status | notes | +| ---- | ----------------------- | --------------------- | --------------------------------- | ------ | ----- | +| [LDAP](Documentation/connectors/ldap.md) | yes | yes | yes | stable | | +| [GitHub](Documentation/connectors/github.md) | yes | yes | yes | stable | | +| [SAML 2.0](Documentation/connectors/saml.md) | no | yes | no | stable | +| [GitLab](Documentation/connectors/gitlab.md) | yes | yes | yes | beta | | +| [OpenID Connect](Documentation/connectors/oidc.md) | yes | no ([#1065][issue-1065]) | no | beta | Includes Google, Salesforce, Azure, etc. | +| [LinkedIn](Documentation/connectors/linkedin.md) | yes | no | no | beta | | +| [Microsoft](Documentation/connectors/microsoft.md) | yes | yes | no | beta | | +| [AuthProxy](Documentation/connectors/authproxy.md) | no | no | no | alpha | Authentication proxies such as Apache2 mod_auth, etc. | +| [Bitbucket Cloud](Documentation/connectors/bitbucketcloud.md) | yes | yes | no | alpha | | Stable, beta, and alpha are defined as: diff --git a/connector/connector.go b/connector/connector.go index edd7fa57..aab994b4 100644 --- a/connector/connector.go +++ b/connector/connector.go @@ -23,10 +23,11 @@ type Scopes struct { // Identity represents the ID Token claims supported by the server. type Identity struct { - UserID string - Username string - Email string - EmailVerified bool + UserID string + Username string + PreferredUsername string + Email string + EmailVerified bool Groups []string diff --git a/connector/github/github.go b/connector/github/github.go index 6fc4cc03..6d915edc 100644 --- a/connector/github/github.go +++ b/connector/github/github.go @@ -266,10 +266,11 @@ func (c *githubConnector) HandleCallback(s connector.Scopes, r *http.Request) (i } identity = connector.Identity{ - UserID: strconv.Itoa(user.ID), - Username: username, - Email: user.Email, - EmailVerified: true, + UserID: strconv.Itoa(user.ID), + Username: username, + PreferredUsername: user.Login, + Email: user.Email, + EmailVerified: true, } if c.useLoginAsID { identity.UserID = user.Login @@ -317,6 +318,7 @@ func (c *githubConnector) Refresh(ctx context.Context, s connector.Scopes, ident username = user.Login } identity.Username = username + identity.PreferredUsername = user.Login identity.Email = user.Email // Only set identity.Groups if 'orgs', 'org', or 'groups' scope are specified. diff --git a/connector/gitlab/gitlab.go b/connector/gitlab/gitlab.go index d9cffded..a9b0abe2 100644 --- a/connector/gitlab/gitlab.go +++ b/connector/gitlab/gitlab.go @@ -147,10 +147,11 @@ func (c *gitlabConnector) HandleCallback(s connector.Scopes, r *http.Request) (i username = user.Email } identity = connector.Identity{ - UserID: strconv.Itoa(user.ID), - Username: username, - Email: user.Email, - EmailVerified: true, + UserID: strconv.Itoa(user.ID), + Username: username, + PreferredUsername: user.Username, + Email: user.Email, + EmailVerified: true, } if c.useLoginAsID { identity.UserID = user.Username @@ -197,6 +198,7 @@ func (c *gitlabConnector) Refresh(ctx context.Context, s connector.Scopes, ident username = user.Email } ident.Username = username + ident.PreferredUsername = user.Username ident.Email = user.Email if c.groupsRequired(s.Groups) { diff --git a/connector/ldap/ldap.go b/connector/ldap/ldap.go index cf8e5006..aed73194 100644 --- a/connector/ldap/ldap.go +++ b/connector/ldap/ldap.go @@ -39,6 +39,7 @@ import ( // idAttr: uid // emailAttr: mail // nameAttr: name +// preferredUsernameAttr: uid // groupSearch: // # Would translate to the query "(&(objectClass=group)(member=))" // baseDN: cn=groups,dc=example,dc=com @@ -103,9 +104,10 @@ type Config struct { Scope string `json:"scope"` // A mapping of attributes on the user entry to claims. - IDAttr string `json:"idAttr"` // Defaults to "uid" - EmailAttr string `json:"emailAttr"` // Defaults to "mail" - NameAttr string `json:"nameAttr"` // No default. + IDAttr string `json:"idAttr"` // Defaults to "uid" + EmailAttr string `json:"emailAttr"` // Defaults to "mail" + NameAttr string `json:"nameAttr"` // No default. + PreferredUsernameAttrAttr string `json:"preferredUsernameAttr"` // No default. // If this is set, the email claim of the id token will be constructed from the idAttr and // value of emailSuffix. This should not include the @ character. @@ -341,6 +343,12 @@ func (c *ldapConnector) identityFromEntry(user ldap.Entry) (ident connector.Iden } } + if c.UserSearch.PreferredUsernameAttrAttr != "" { + if ident.PreferredUsername = getAttr(user, c.UserSearch.PreferredUsernameAttrAttr); ident.PreferredUsername == "" { + missing = append(missing, c.UserSearch.PreferredUsernameAttrAttr) + } + } + if c.UserSearch.EmailSuffix != "" { ident.Email = ident.Username + "@" + c.UserSearch.EmailSuffix } else if ident.Email = getAttr(user, c.UserSearch.EmailAttr); ident.Email == "" { @@ -381,6 +389,10 @@ func (c *ldapConnector) userEntry(conn *ldap.Conn, username string) (user ldap.E req.Attributes = append(req.Attributes, c.UserSearch.NameAttr) } + if c.UserSearch.PreferredUsernameAttrAttr != "" { + req.Attributes = append(req.Attributes, c.UserSearch.PreferredUsernameAttrAttr) + } + c.logger.Infof("performing ldap search %s %s %s", req.BaseDN, scopeString(req.Scope), req.Filter) resp, err := conn.Search(req) diff --git a/server/handlers.go b/server/handlers.go index 1391e589..ba34934a 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -479,11 +479,12 @@ func (s *Server) handleConnectorCallback(w http.ResponseWriter, r *http.Request) // the approval page's path. func (s *Server) finalizeLogin(identity connector.Identity, authReq storage.AuthRequest, conn connector.Connector) (string, error) { claims := storage.Claims{ - UserID: identity.UserID, - Username: identity.Username, - Email: identity.Email, - EmailVerified: identity.EmailVerified, - Groups: identity.Groups, + UserID: identity.UserID, + Username: identity.Username, + PreferredUsername: identity.PreferredUsername, + Email: identity.Email, + EmailVerified: identity.EmailVerified, + Groups: identity.Groups, } updater := func(a storage.AuthRequest) (storage.AuthRequest, error) { @@ -501,8 +502,8 @@ func (s *Server) finalizeLogin(identity connector.Identity, authReq storage.Auth email = email + " (unverified)" } - s.logger.Infof("login successful: connector %q, username=%q, email=%q, groups=%q", - authReq.ConnectorID, claims.Username, email, claims.Groups) + s.logger.Infof("login successful: connector %q, username=%q, preferred_username=%q, email=%q, groups=%q", + authReq.ConnectorID, claims.Username, claims.PreferredUsername, claims.Email, claims.Groups) return path.Join(s.issuerURL.Path, "/approval") + "?req=" + authReq.ID, nil } @@ -992,11 +993,12 @@ func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, clie } claims := storage.Claims{ - UserID: ident.UserID, - Username: ident.Username, - Email: ident.Email, - EmailVerified: ident.EmailVerified, - Groups: ident.Groups, + UserID: ident.UserID, + Username: ident.Username, + PreferredUsername: ident.PreferredUsername, + Email: ident.Email, + EmailVerified: ident.EmailVerified, + Groups: ident.Groups, } accessToken, err := s.newAccessToken(client.ID, claims, scopes, refresh.Nonce, refresh.ConnectorID) diff --git a/server/oauth2.go b/server/oauth2.go index 6104b549..0cd26814 100644 --- a/server/oauth2.go +++ b/server/oauth2.go @@ -258,7 +258,8 @@ type idTokenClaims struct { Groups []string `json:"groups,omitempty"` - Name string `json:"name,omitempty"` + Name string `json:"name,omitempty"` + PreferredUsername string `json:"preferred_username,omitempty"` FederatedIDClaims *federatedIDClaims `json:"federated_claims,omitempty"` } @@ -329,6 +330,7 @@ func (s *Server) newIDToken(clientID string, claims storage.Claims, scopes []str tok.Groups = claims.Groups case scope == scopeProfile: tok.Name = claims.Username + tok.PreferredUsername = claims.PreferredUsername case scope == scopeFederatedID: tok.FederatedIDClaims = &federatedIDClaims{ ConnectorID: connID, diff --git a/storage/etcd/types.go b/storage/etcd/types.go index 0d8f521a..8063c69f 100644 --- a/storage/etcd/types.go +++ b/storage/etcd/types.go @@ -148,30 +148,33 @@ func fromStorageRefreshToken(r storage.RefreshToken) RefreshToken { // Claims is a mirrored struct from storage with JSON struct tags. type Claims struct { - UserID string `json:"userID"` - Username string `json:"username"` - Email string `json:"email"` - EmailVerified bool `json:"emailVerified"` - Groups []string `json:"groups,omitempty"` + UserID string `json:"userID"` + Username string `json:"username"` + PreferredUsername string `json:"preferredUsername"` + Email string `json:"email"` + EmailVerified bool `json:"emailVerified"` + Groups []string `json:"groups,omitempty"` } func fromStorageClaims(i storage.Claims) Claims { return Claims{ - UserID: i.UserID, - Username: i.Username, - Email: i.Email, - EmailVerified: i.EmailVerified, - Groups: i.Groups, + UserID: i.UserID, + Username: i.Username, + PreferredUsername: i.PreferredUsername, + Email: i.Email, + EmailVerified: i.EmailVerified, + Groups: i.Groups, } } func toStorageClaims(i Claims) storage.Claims { return storage.Claims{ - UserID: i.UserID, - Username: i.Username, - Email: i.Email, - EmailVerified: i.EmailVerified, - Groups: i.Groups, + UserID: i.UserID, + Username: i.Username, + PreferredUsername: i.PreferredUsername, + Email: i.Email, + EmailVerified: i.EmailVerified, + Groups: i.Groups, } } diff --git a/storage/kubernetes/types.go b/storage/kubernetes/types.go index 1ed405b5..a42238b3 100644 --- a/storage/kubernetes/types.go +++ b/storage/kubernetes/types.go @@ -210,30 +210,33 @@ func toStorageClient(c Client) storage.Client { // Claims is a mirrored struct from storage with JSON struct tags. type Claims struct { - UserID string `json:"userID"` - Username string `json:"username"` - Email string `json:"email"` - EmailVerified bool `json:"emailVerified"` - Groups []string `json:"groups,omitempty"` + UserID string `json:"userID"` + Username string `json:"username"` + PreferredUsername string `json:"preferredUsername"` + Email string `json:"email"` + EmailVerified bool `json:"emailVerified"` + Groups []string `json:"groups,omitempty"` } func fromStorageClaims(i storage.Claims) Claims { return Claims{ - UserID: i.UserID, - Username: i.Username, - Email: i.Email, - EmailVerified: i.EmailVerified, - Groups: i.Groups, + UserID: i.UserID, + Username: i.Username, + PreferredUsername: i.PreferredUsername, + Email: i.Email, + EmailVerified: i.EmailVerified, + Groups: i.Groups, } } func toStorageClaims(i Claims) storage.Claims { return storage.Claims{ - UserID: i.UserID, - Username: i.Username, - Email: i.Email, - EmailVerified: i.EmailVerified, - Groups: i.Groups, + UserID: i.UserID, + Username: i.Username, + PreferredUsername: i.PreferredUsername, + Email: i.Email, + EmailVerified: i.EmailVerified, + Groups: i.Groups, } } diff --git a/storage/sql/crud.go b/storage/sql/crud.go index d7c055ab..e1982928 100644 --- a/storage/sql/crud.go +++ b/storage/sql/crud.go @@ -108,19 +108,19 @@ func (c *conn) CreateAuthRequest(a storage.AuthRequest) error { insert into auth_request ( id, client_id, response_types, scopes, redirect_uri, nonce, state, force_approval_prompt, logged_in, - claims_user_id, claims_username, claims_email, claims_email_verified, - claims_groups, + claims_user_id, claims_username, claims_preferred_username, + claims_email, claims_email_verified, claims_groups, connector_id, connector_data, expiry ) values ( - $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17 + $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18 ); `, a.ID, a.ClientID, encoder(a.ResponseTypes), encoder(a.Scopes), a.RedirectURI, a.Nonce, a.State, a.ForceApprovalPrompt, a.LoggedIn, - a.Claims.UserID, a.Claims.Username, a.Claims.Email, a.Claims.EmailVerified, - encoder(a.Claims.Groups), + a.Claims.UserID, a.Claims.Username, a.Claims.PreferredUsername, + a.Claims.Email, a.Claims.EmailVerified, encoder(a.Claims.Groups), a.ConnectorID, a.ConnectorData, a.Expiry, ) @@ -149,16 +149,17 @@ func (c *conn) UpdateAuthRequest(id string, updater func(a storage.AuthRequest) set client_id = $1, response_types = $2, scopes = $3, redirect_uri = $4, nonce = $5, state = $6, force_approval_prompt = $7, logged_in = $8, - claims_user_id = $9, claims_username = $10, claims_email = $11, - claims_email_verified = $12, - claims_groups = $13, - connector_id = $14, connector_data = $15, - expiry = $16 - where id = $17; + claims_user_id = $9, claims_username = $10, claims_preferred_username = $11, + claims_email = $12, claims_email_verified = $13, + claims_groups = $14, + connector_id = $15, connector_data = $16, + expiry = $17 + where id = $18; `, a.ClientID, encoder(a.ResponseTypes), encoder(a.Scopes), a.RedirectURI, a.Nonce, a.State, a.ForceApprovalPrompt, a.LoggedIn, - a.Claims.UserID, a.Claims.Username, a.Claims.Email, a.Claims.EmailVerified, + a.Claims.UserID, a.Claims.Username, a.Claims.PreferredUsername, + a.Claims.Email, a.Claims.EmailVerified, encoder(a.Claims.Groups), a.ConnectorID, a.ConnectorData, a.Expiry, r.ID, @@ -180,14 +181,15 @@ func getAuthRequest(q querier, id string) (a storage.AuthRequest, err error) { select id, client_id, response_types, scopes, redirect_uri, nonce, state, force_approval_prompt, logged_in, - claims_user_id, claims_username, claims_email, claims_email_verified, - claims_groups, + claims_user_id, claims_username, claims_preferred_username, + claims_email, claims_email_verified, claims_groups, connector_id, connector_data, expiry from auth_request where id = $1; `, id).Scan( &a.ID, &a.ClientID, decoder(&a.ResponseTypes), decoder(&a.Scopes), &a.RedirectURI, &a.Nonce, &a.State, &a.ForceApprovalPrompt, &a.LoggedIn, - &a.Claims.UserID, &a.Claims.Username, &a.Claims.Email, &a.Claims.EmailVerified, + &a.Claims.UserID, &a.Claims.Username, &a.Claims.PreferredUsername, + &a.Claims.Email, &a.Claims.EmailVerified, decoder(&a.Claims.Groups), &a.ConnectorID, &a.ConnectorData, &a.Expiry, ) @@ -204,16 +206,16 @@ func (c *conn) CreateAuthCode(a storage.AuthCode) error { _, err := c.Exec(` insert into auth_code ( id, client_id, scopes, nonce, redirect_uri, - claims_user_id, claims_username, + claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, connector_id, connector_data, expiry ) - values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13); + values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14); `, a.ID, a.ClientID, encoder(a.Scopes), a.Nonce, a.RedirectURI, a.Claims.UserID, - a.Claims.Username, a.Claims.Email, a.Claims.EmailVerified, encoder(a.Claims.Groups), - a.ConnectorID, a.ConnectorData, a.Expiry, + a.Claims.Username, a.Claims.PreferredUsername, a.Claims.Email, a.Claims.EmailVerified, + encoder(a.Claims.Groups), a.ConnectorID, a.ConnectorData, a.Expiry, ) if err != nil { @@ -229,15 +231,15 @@ func (c *conn) GetAuthCode(id string) (a storage.AuthCode, err error) { err = c.QueryRow(` select id, client_id, scopes, nonce, redirect_uri, - claims_user_id, claims_username, + claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, connector_id, connector_data, expiry from auth_code where id = $1; `, id).Scan( &a.ID, &a.ClientID, decoder(&a.Scopes), &a.Nonce, &a.RedirectURI, &a.Claims.UserID, - &a.Claims.Username, &a.Claims.Email, &a.Claims.EmailVerified, decoder(&a.Claims.Groups), - &a.ConnectorID, &a.ConnectorData, &a.Expiry, + &a.Claims.Username, &a.Claims.PreferredUsername, &a.Claims.Email, &a.Claims.EmailVerified, + decoder(&a.Claims.Groups), &a.ConnectorID, &a.ConnectorData, &a.Expiry, ) if err != nil { if err == sql.ErrNoRows { @@ -252,15 +254,16 @@ func (c *conn) CreateRefresh(r storage.RefreshToken) error { _, err := c.Exec(` insert into refresh_token ( id, client_id, scopes, nonce, - claims_user_id, claims_username, claims_email, claims_email_verified, - claims_groups, + claims_user_id, claims_username, claims_preferred_username, + claims_email, claims_email_verified, claims_groups, connector_id, connector_data, token, created_at, last_used ) - values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14); + values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15); `, r.ID, r.ClientID, encoder(r.Scopes), r.Nonce, - r.Claims.UserID, r.Claims.Username, r.Claims.Email, r.Claims.EmailVerified, + r.Claims.UserID, r.Claims.Username, r.Claims.PreferredUsername, + r.Claims.Email, r.Claims.EmailVerified, encoder(r.Claims.Groups), r.ConnectorID, r.ConnectorData, r.Token, r.CreatedAt, r.LastUsed, @@ -291,19 +294,21 @@ func (c *conn) UpdateRefreshToken(id string, updater func(old storage.RefreshTok nonce = $3, claims_user_id = $4, claims_username = $5, - claims_email = $6, - claims_email_verified = $7, - claims_groups = $8, - connector_id = $9, - connector_data = $10, - token = $11, - created_at = $12, - last_used = $13 + claims_preferred_username = $6, + claims_email = $7, + claims_email_verified = $8, + claims_groups = $9, + connector_id = $10, + connector_data = $11, + token = $12, + created_at = $13, + last_used = $14 where - id = $14 + id = $15 `, r.ClientID, encoder(r.Scopes), r.Nonce, - r.Claims.UserID, r.Claims.Username, r.Claims.Email, r.Claims.EmailVerified, + r.Claims.UserID, r.Claims.Username, r.Claims.PreferredUsername, + r.Claims.Email, r.Claims.EmailVerified, encoder(r.Claims.Groups), r.ConnectorID, r.ConnectorData, r.Token, r.CreatedAt, r.LastUsed, id, @@ -323,7 +328,8 @@ func getRefresh(q querier, id string) (storage.RefreshToken, error) { return scanRefresh(q.QueryRow(` select id, client_id, scopes, nonce, - claims_user_id, claims_username, claims_email, claims_email_verified, + claims_user_id, claims_username, claims_preferred_username, + claims_email, claims_email_verified, claims_groups, connector_id, connector_data, token, created_at, last_used @@ -335,8 +341,8 @@ func (c *conn) ListRefreshTokens() ([]storage.RefreshToken, error) { rows, err := c.Query(` select id, client_id, scopes, nonce, - claims_user_id, claims_username, claims_email, claims_email_verified, - claims_groups, + claims_user_id, claims_username, claims_preferred_username, + claims_email, claims_email_verified, claims_groups, connector_id, connector_data, token, created_at, last_used from refresh_token; @@ -361,7 +367,8 @@ func (c *conn) ListRefreshTokens() ([]storage.RefreshToken, error) { func scanRefresh(s scanner) (r storage.RefreshToken, err error) { err = s.Scan( &r.ID, &r.ClientID, decoder(&r.Scopes), &r.Nonce, - &r.Claims.UserID, &r.Claims.Username, &r.Claims.Email, &r.Claims.EmailVerified, + &r.Claims.UserID, &r.Claims.Username, &r.Claims.PreferredUsername, + &r.Claims.Email, &r.Claims.EmailVerified, decoder(&r.Claims.Groups), &r.ConnectorID, &r.ConnectorData, &r.Token, &r.CreatedAt, &r.LastUsed, diff --git a/storage/sql/migrate.go b/storage/sql/migrate.go index e30629e7..0ef62609 100644 --- a/storage/sql/migrate.go +++ b/storage/sql/migrate.go @@ -190,4 +190,16 @@ var migrations = []migration{ );`, }, }, + { + stmts: []string{` + alter table auth_code + add column claims_preferred_username text not null default '';`, + ` + alter table auth_request + add column claims_preferred_username text not null default '';`, + ` + alter table refresh_token + add column claims_preferred_username text not null default '';`, + }, + }, } diff --git a/storage/storage.go b/storage/storage.go index 893fb100..235f74e0 100644 --- a/storage/storage.go +++ b/storage/storage.go @@ -137,10 +137,11 @@ type Client struct { // Claims represents the ID Token claims supported by the server. type Claims struct { - UserID string - Username string - Email string - EmailVerified bool + UserID string + Username string + PreferredUsername string + Email string + EmailVerified bool Groups []string } From 0b55f121b4f7a38f277631910869d5f89e2c05ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?N=C3=A1ndor=20Istv=C3=A1n=20Kr=C3=A1cser?= Date: Wed, 30 Oct 2019 13:13:33 +0100 Subject: [PATCH 13/72] Fix missing email in log message Co-Authored-By: Felix Fontein --- server/handlers.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/handlers.go b/server/handlers.go index ba34934a..e7020670 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -503,7 +503,7 @@ func (s *Server) finalizeLogin(identity connector.Identity, authReq storage.Auth } s.logger.Infof("login successful: connector %q, username=%q, preferred_username=%q, email=%q, groups=%q", - authReq.ConnectorID, claims.Username, claims.PreferredUsername, claims.Email, claims.Groups) + authReq.ConnectorID, claims.Username, claims.PreferredUsername, email, claims.Groups) return path.Join(s.issuerURL.Path, "/approval") + "?req=" + authReq.ID, nil } From b793afd375b19f955db8163c4b12c0de3de714cf Mon Sep 17 00:00:00 2001 From: serhiimakogon Date: Tue, 19 Nov 2019 16:27:34 +0200 Subject: [PATCH 14/72] preferred_username claim added on refresh token --- server/handlers.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/server/handlers.go b/server/handlers.go index e7020670..b528918f 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -969,12 +969,13 @@ func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, clie return } ident := connector.Identity{ - UserID: refresh.Claims.UserID, - Username: refresh.Claims.Username, - Email: refresh.Claims.Email, - EmailVerified: refresh.Claims.EmailVerified, - Groups: refresh.Claims.Groups, - ConnectorData: refresh.ConnectorData, + UserID: refresh.Claims.UserID, + Username: refresh.Claims.Username, + PreferredUsername: refresh.Claims.PreferredUsername, + Email: refresh.Claims.Email, + EmailVerified: refresh.Claims.EmailVerified, + Groups: refresh.Claims.Groups, + ConnectorData: refresh.ConnectorData, } // Can the connector refresh the identity? If so, attempt to refresh the data @@ -1036,6 +1037,7 @@ func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, clie // // UserID intentionally ignored for now. old.Claims.Username = ident.Username + old.Claims.PreferredUsername = ident.PreferredUsername old.Claims.Email = ident.Email old.Claims.EmailVerified = ident.EmailVerified old.Claims.Groups = ident.Groups From 575c792156e25e0f71cc3d4781489706e76a21eb Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Sun, 28 Jan 2018 22:37:07 +0000 Subject: [PATCH 15/72] Store most recent refresh token in offline sessions --- server/handlers.go | 33 +++++++++++++++++++++++++++++++++ storage/storage.go | 3 +++ 2 files changed, 36 insertions(+) diff --git a/server/handlers.go b/server/handlers.go index b528918f..3be6f380 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -505,6 +505,39 @@ func (s *Server) finalizeLogin(identity connector.Identity, authReq storage.Auth s.logger.Infof("login successful: connector %q, username=%q, preferred_username=%q, email=%q, groups=%q", authReq.ConnectorID, claims.Username, claims.PreferredUsername, email, claims.Groups) + if _, ok := conn.(connector.RefreshConnector); ok { + // Try to retrieve an existing OfflineSession object for the corresponding user. + if session, err := s.storage.GetOfflineSessions(identity.UserID, authReq.ConnectorID); err != nil { + if err != storage.ErrNotFound { + s.logger.Errorf("failed to get offline session: %v", err) + return "", err + } + offlineSessions := storage.OfflineSessions{ + UserID: identity.UserID, + ConnID: authReq.ConnectorID, + Refresh: make(map[string]*storage.RefreshTokenRef), + ConnectorData: identity.ConnectorData, + } + + // Create a new OfflineSession object for the user and add a reference object for + // the newly received refreshtoken. + if err := s.storage.CreateOfflineSessions(offlineSessions); err != nil { + s.logger.Errorf("failed to create offline session: %v", err) + return "", err + } + } else { + // Update existing OfflineSession obj with new RefreshTokenRef. + if err := s.storage.UpdateOfflineSessions(session.UserID, session.ConnID, func(old storage.OfflineSessions) (storage.OfflineSessions, error) { + old.ConnectorData = identity.ConnectorData + return old, nil + }); err != nil { + s.logger.Errorf("failed to update offline session: %v", err) + return "", err + } + + } + } + return path.Join(s.issuerURL.Path, "/approval") + "?req=" + authReq.ID, nil } diff --git a/storage/storage.go b/storage/storage.go index 235f74e0..cb2a7e0c 100644 --- a/storage/storage.go +++ b/storage/storage.go @@ -273,6 +273,9 @@ type OfflineSessions struct { // Refresh is a hash table of refresh token reference objects // indexed by the ClientID of the refresh token. Refresh map[string]*RefreshTokenRef + + // Authentication data provided by an upstream source. + ConnectorData []byte } // Password is an email to password mapping managed by the storage. From 0352258093d4882adc6ad480d7de5816ee8d2b82 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Mon, 29 Jan 2018 20:46:18 +0000 Subject: [PATCH 16/72] Update handleRefreshToken logic --- server/handlers.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/server/handlers.go b/server/handlers.go index 3be6f380..1c320b29 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -995,6 +995,16 @@ func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, clie scopes = requestedScopes } + var connectorData []byte + if session, err := s.storage.GetOfflineSessions(refresh.Claims.UserID, refresh.ConnectorID); err != nil { + if err != storage.ErrNotFound { + s.logger.Errorf("failed to get offline session: %v", err) + return + } + } else { + connectorData = session.ConnectorData + } + conn, err := s.getConnector(refresh.ConnectorID) if err != nil { s.logger.Errorf("connector with ID %q not found: %v", refresh.ConnectorID, err) @@ -1008,7 +1018,7 @@ func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, clie Email: refresh.Claims.Email, EmailVerified: refresh.Claims.EmailVerified, Groups: refresh.Claims.Groups, - ConnectorData: refresh.ConnectorData, + ConnectorData: connectorData, } // Can the connector refresh the identity? If so, attempt to refresh the data @@ -1074,7 +1084,6 @@ func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, clie old.Claims.Email = ident.Email old.Claims.EmailVerified = ident.EmailVerified old.Claims.Groups = ident.Groups - old.ConnectorData = ident.ConnectorData old.LastUsed = lastUsed return old, nil } @@ -1086,6 +1095,7 @@ func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, clie return old, errors.New("refresh token invalid") } old.Refresh[refresh.ClientID].LastUsed = lastUsed + old.ConnectorData = ident.ConnectorData return old, nil }); err != nil { s.logger.Errorf("failed to update offline session: %v", err) From 5c8871317748cb76f6000c03af1095604a09235a Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Mon, 29 Jan 2018 20:48:40 +0000 Subject: [PATCH 17/72] Remove connectordata from other structs --- server/api_test.go | 1 - server/handlers.go | 37 +++++++++++++++++-------------------- storage/storage.go | 13 +++++-------- 3 files changed, 22 insertions(+), 29 deletions(-) diff --git a/server/api_test.go b/server/api_test.go index 80a22486..a7891208 100644 --- a/server/api_test.go +++ b/server/api_test.go @@ -259,7 +259,6 @@ func TestRefreshToken(t *testing.T) { EmailVerified: true, Groups: []string{"a", "b"}, }, - ConnectorData: []byte(`{"some":"data"}`), } if err := s.CreateRefresh(r); err != nil { diff --git a/server/handlers.go b/server/handlers.go index 1c320b29..08bf5d04 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -490,7 +490,6 @@ func (s *Server) finalizeLogin(identity connector.Identity, authReq storage.Auth updater := func(a storage.AuthRequest) (storage.AuthRequest, error) { a.LoggedIn = true a.Claims = claims - a.ConnectorData = identity.ConnectorData return a, nil } if err := s.storage.UpdateAuthRequest(authReq.ID, updater); err != nil { @@ -620,15 +619,14 @@ func (s *Server) sendCodeResponse(w http.ResponseWriter, r *http.Request, authRe switch responseType { case responseTypeCode: code = storage.AuthCode{ - ID: storage.NewID(), - ClientID: authReq.ClientID, - ConnectorID: authReq.ConnectorID, - Nonce: authReq.Nonce, - Scopes: authReq.Scopes, - Claims: authReq.Claims, - Expiry: s.now().Add(time.Minute * 30), - RedirectURI: authReq.RedirectURI, - ConnectorData: authReq.ConnectorData, + ID: storage.NewID(), + ClientID: authReq.ClientID, + ConnectorID: authReq.ConnectorID, + Nonce: authReq.Nonce, + Scopes: authReq.Scopes, + Claims: authReq.Claims, + Expiry: s.now().Add(time.Minute * 30), + RedirectURI: authReq.RedirectURI, } if err := s.storage.CreateAuthCode(code); err != nil { s.logger.Errorf("Failed to create auth code: %v", err) @@ -824,16 +822,15 @@ func (s *Server) handleAuthCode(w http.ResponseWriter, r *http.Request, client s var refreshToken string if reqRefresh { refresh := storage.RefreshToken{ - ID: storage.NewID(), - Token: storage.NewID(), - ClientID: authCode.ClientID, - ConnectorID: authCode.ConnectorID, - Scopes: authCode.Scopes, - Claims: authCode.Claims, - Nonce: authCode.Nonce, - ConnectorData: authCode.ConnectorData, - CreatedAt: s.now(), - LastUsed: s.now(), + ID: storage.NewID(), + Token: storage.NewID(), + ClientID: authCode.ClientID, + ConnectorID: authCode.ConnectorID, + Scopes: authCode.Scopes, + Claims: authCode.Claims, + Nonce: authCode.Nonce, + CreatedAt: s.now(), + LastUsed: s.now(), } token := &internal.RefreshToken{ RefreshId: refresh.ID, diff --git a/storage/storage.go b/storage/storage.go index cb2a7e0c..85a60965 100644 --- a/storage/storage.go +++ b/storage/storage.go @@ -181,8 +181,7 @@ type AuthRequest struct { // The connector used to login the user and any data the connector wishes to persists. // Set when the user authenticates. - ConnectorID string - ConnectorData []byte + ConnectorID string } // AuthCode represents a code which can be exchanged for an OAuth2 token response. @@ -213,9 +212,8 @@ type AuthCode struct { Scopes []string // Authentication data provided by an upstream source. - ConnectorID string - ConnectorData []byte - Claims Claims + ConnectorID string + Claims Claims Expiry time.Time } @@ -237,9 +235,8 @@ type RefreshToken struct { ClientID string // Authentication data provided by an upstream source. - ConnectorID string - ConnectorData []byte - Claims Claims + ConnectorID string + Claims Claims // Scopes present in the initial request. Refresh requests may specify a set // of scopes different from the initial request when refreshing a token, From 0857a0fe09a7dd9e45b26d966ce2ef84d7e7545a Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Mon, 29 Jan 2018 21:07:15 +0000 Subject: [PATCH 18/72] Implement refresh in OIDC connector This has added the access=offline parameter and prompt=consent parameter to the initial request, this works with google, assuming other providers will ignore the prompt parameter --- connector/oidc/oidc.go | 55 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/connector/oidc/oidc.go b/connector/oidc/oidc.go index b5e075ad..dfab061a 100644 --- a/connector/oidc/oidc.go +++ b/connector/oidc/oidc.go @@ -9,6 +9,7 @@ import ( "net/url" "strings" "sync" + "time" "github.com/coreos/go-oidc" "golang.org/x/oauth2" @@ -172,9 +173,9 @@ func (c *oidcConnector) LoginURL(s connector.Scopes, callbackURL, state string) if len(c.hostedDomains) > 1 { preferredDomain = "*" } - return c.oauth2Config.AuthCodeURL(state, oauth2.SetAuthURLParam("hd", preferredDomain)), nil + return c.oauth2Config.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("prompt", "consent"), oauth2.SetAuthURLParam("hd", preferredDomain)), nil } - return c.oauth2Config.AuthCodeURL(state), nil + return c.oauth2Config.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("prompt", "consent")), nil } type oauth2Error struct { @@ -265,6 +266,7 @@ func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (ide Username: name, Email: email, EmailVerified: emailVerified, + ConnectorData: []byte(token.RefreshToken), } if c.userIDKey != "" { @@ -280,5 +282,54 @@ func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (ide // Refresh is implemented for backwards compatibility, even though it's a no-op. func (c *oidcConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) { + t := &oauth2.Token{ + RefreshToken: string(identity.ConnectorData), + Expiry: time.Now().Add(-time.Hour), + } + token, err := c.oauth2Config.TokenSource(ctx, t).Token() + if err != nil { + return identity, fmt.Errorf("oidc: failed to get token: %v", err) + } + + rawIDToken, ok := token.Extra("id_token").(string) + if !ok { + return identity, errors.New("oidc: no id_token in token response") + } + idToken, err := c.verifier.Verify(ctx, rawIDToken) + if err != nil { + return identity, fmt.Errorf("oidc: failed to verify ID Token: %v", err) + } + + var claims struct { + Username string `json:"name"` + Email string `json:"email"` + EmailVerified bool `json:"email_verified"` + HostedDomain string `json:"hd"` + } + if err := idToken.Claims(&claims); err != nil { + return identity, fmt.Errorf("oidc: failed to decode claims: %v", err) + } + + if len(c.hostedDomains) > 0 { + found := false + for _, domain := range c.hostedDomains { + if claims.HostedDomain == domain { + found = true + break + } + } + + if !found { + return identity, fmt.Errorf("oidc: unexpected hd claim %v", claims.HostedDomain) + } + } + + identity = connector.Identity{ + UserID: idToken.Subject, + Username: claims.Username, + Email: claims.Email, + EmailVerified: claims.EmailVerified, + ConnectorData: []byte(token.RefreshToken), + } return identity, nil } From 7fc3f230df81a30dd29e1bd72f79a908cdcc8ebb Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Mon, 29 Jan 2018 21:07:46 +0000 Subject: [PATCH 19/72] Update SQL storage backend --- storage/sql/crud.go | 70 ++++++++++++++++++++++----------------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/storage/sql/crud.go b/storage/sql/crud.go index e1982928..26a42176 100644 --- a/storage/sql/crud.go +++ b/storage/sql/crud.go @@ -108,20 +108,20 @@ func (c *conn) CreateAuthRequest(a storage.AuthRequest) error { insert into auth_request ( id, client_id, response_types, scopes, redirect_uri, nonce, state, force_approval_prompt, logged_in, - claims_user_id, claims_username, claims_preferred_username, + claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, - connector_id, connector_data, + connector_id, expiry ) values ( - $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18 + $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17 ); `, a.ID, a.ClientID, encoder(a.ResponseTypes), encoder(a.Scopes), a.RedirectURI, a.Nonce, a.State, a.ForceApprovalPrompt, a.LoggedIn, a.Claims.UserID, a.Claims.Username, a.Claims.PreferredUsername, a.Claims.Email, a.Claims.EmailVerified, encoder(a.Claims.Groups), - a.ConnectorID, a.ConnectorData, + a.ConnectorID, a.Expiry, ) if err != nil { @@ -152,16 +152,16 @@ func (c *conn) UpdateAuthRequest(id string, updater func(a storage.AuthRequest) claims_user_id = $9, claims_username = $10, claims_preferred_username = $11, claims_email = $12, claims_email_verified = $13, claims_groups = $14, - connector_id = $15, connector_data = $16, - expiry = $17 - where id = $18; + connector_id = $15, + expiry = $16 + where id = $17; `, a.ClientID, encoder(a.ResponseTypes), encoder(a.Scopes), a.RedirectURI, a.Nonce, a.State, a.ForceApprovalPrompt, a.LoggedIn, a.Claims.UserID, a.Claims.Username, a.Claims.PreferredUsername, a.Claims.Email, a.Claims.EmailVerified, encoder(a.Claims.Groups), - a.ConnectorID, a.ConnectorData, + a.ConnectorID, a.Expiry, r.ID, ) if err != nil { @@ -178,12 +178,12 @@ func (c *conn) GetAuthRequest(id string) (storage.AuthRequest, error) { func getAuthRequest(q querier, id string) (a storage.AuthRequest, err error) { err = q.QueryRow(` - select + select id, client_id, response_types, scopes, redirect_uri, nonce, state, force_approval_prompt, logged_in, claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, - connector_id, connector_data, expiry + connector_id, expiry from auth_request where id = $1; `, id).Scan( &a.ID, &a.ClientID, decoder(&a.ResponseTypes), decoder(&a.Scopes), &a.RedirectURI, &a.Nonce, &a.State, @@ -191,7 +191,7 @@ func getAuthRequest(q querier, id string) (a storage.AuthRequest, err error) { &a.Claims.UserID, &a.Claims.Username, &a.Claims.PreferredUsername, &a.Claims.Email, &a.Claims.EmailVerified, decoder(&a.Claims.Groups), - &a.ConnectorID, &a.ConnectorData, &a.Expiry, + &a.ConnectorID, &a.Expiry, ) if err != nil { if err == sql.ErrNoRows { @@ -208,14 +208,14 @@ func (c *conn) CreateAuthCode(a storage.AuthCode) error { id, client_id, scopes, nonce, redirect_uri, claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, - connector_id, connector_data, + connector_id, expiry ) - values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14); + values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13); `, a.ID, a.ClientID, encoder(a.Scopes), a.Nonce, a.RedirectURI, a.Claims.UserID, a.Claims.Username, a.Claims.PreferredUsername, a.Claims.Email, a.Claims.EmailVerified, - encoder(a.Claims.Groups), a.ConnectorID, a.ConnectorData, a.Expiry, + encoder(a.Claims.Groups), a.ConnectorID, a.Expiry, ) if err != nil { @@ -233,13 +233,13 @@ func (c *conn) GetAuthCode(id string) (a storage.AuthCode, err error) { id, client_id, scopes, nonce, redirect_uri, claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, - connector_id, connector_data, + connector_id, expiry from auth_code where id = $1; `, id).Scan( &a.ID, &a.ClientID, decoder(&a.Scopes), &a.Nonce, &a.RedirectURI, &a.Claims.UserID, &a.Claims.Username, &a.Claims.PreferredUsername, &a.Claims.Email, &a.Claims.EmailVerified, - decoder(&a.Claims.Groups), &a.ConnectorID, &a.ConnectorData, &a.Expiry, + decoder(&a.Claims.Groups), &a.ConnectorID, &a.Expiry, ) if err != nil { if err == sql.ErrNoRows { @@ -256,16 +256,16 @@ func (c *conn) CreateRefresh(r storage.RefreshToken) error { id, client_id, scopes, nonce, claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, - connector_id, connector_data, + connector_id, token, created_at, last_used ) - values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15); + values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14); `, r.ID, r.ClientID, encoder(r.Scopes), r.Nonce, r.Claims.UserID, r.Claims.Username, r.Claims.PreferredUsername, r.Claims.Email, r.Claims.EmailVerified, encoder(r.Claims.Groups), - r.ConnectorID, r.ConnectorData, + r.ConnectorID, r.Token, r.CreatedAt, r.LastUsed, ) if err != nil { @@ -299,18 +299,17 @@ func (c *conn) UpdateRefreshToken(id string, updater func(old storage.RefreshTok claims_email_verified = $8, claims_groups = $9, connector_id = $10, - connector_data = $11, - token = $12, - created_at = $13, - last_used = $14 + token = $11, + created_at = $12, + last_used = $13 where - id = $15 + id = $14 `, r.ClientID, encoder(r.Scopes), r.Nonce, r.Claims.UserID, r.Claims.Username, r.Claims.PreferredUsername, r.Claims.Email, r.Claims.EmailVerified, encoder(r.Claims.Groups), - r.ConnectorID, r.ConnectorData, + r.ConnectorID, r.Token, r.CreatedAt, r.LastUsed, id, ) if err != nil { @@ -370,7 +369,7 @@ func scanRefresh(s scanner) (r storage.RefreshToken, err error) { &r.Claims.UserID, &r.Claims.Username, &r.Claims.PreferredUsername, &r.Claims.Email, &r.Claims.EmailVerified, decoder(&r.Claims.Groups), - &r.ConnectorID, &r.ConnectorData, + &r.ConnectorID, &r.Token, &r.CreatedAt, &r.LastUsed, ) if err != nil { @@ -417,7 +416,7 @@ func (c *conn) UpdateKeys(updater func(old storage.Keys) (storage.Keys, error)) } else { _, err = tx.Exec(` update keys - set + set verification_keys = $1, signing_key = $2, signing_key_pub = $3, @@ -655,13 +654,13 @@ func scanPassword(s scanner) (p storage.Password, err error) { func (c *conn) CreateOfflineSessions(s storage.OfflineSessions) error { _, err := c.Exec(` insert into offline_session ( - user_id, conn_id, refresh + user_id, conn_id, refresh, connector_data ) values ( - $1, $2, $3 + $1, $2, $3, $4 ); `, - s.UserID, s.ConnID, encoder(s.Refresh), + s.UserID, s.ConnID, encoder(s.Refresh), s.ConnectorData, ) if err != nil { if c.alreadyExistsCheck(err) { @@ -687,9 +686,10 @@ func (c *conn) UpdateOfflineSessions(userID string, connID string, updater func( update offline_session set refresh = $1 - where user_id = $2 AND conn_id = $3; + connector_data = $2 + where user_id = $3 AND conn_id = $4; `, - encoder(newSession.Refresh), s.UserID, s.ConnID, + encoder(newSession.Refresh), s.ConnectorData, s.UserID, s.ConnID, ) if err != nil { return fmt.Errorf("update offline session: %v", err) @@ -705,7 +705,7 @@ func (c *conn) GetOfflineSessions(userID string, connID string) (storage.Offline func getOfflineSessions(q querier, userID string, connID string) (storage.OfflineSessions, error) { return scanOfflineSessions(q.QueryRow(` select - user_id, conn_id, refresh + user_id, conn_id, refresh, connector_data from offline_session where user_id = $1 AND conn_id = $2; `, userID, connID)) @@ -713,7 +713,7 @@ func getOfflineSessions(q querier, userID string, connID string) (storage.Offlin func scanOfflineSessions(s scanner) (o storage.OfflineSessions, err error) { err = s.Scan( - &o.UserID, &o.ConnID, decoder(&o.Refresh), + &o.UserID, &o.ConnID, decoder(&o.Refresh), &o.ConnectorData, ) if err != nil { if err == sql.ErrNoRows { @@ -757,7 +757,7 @@ func (c *conn) UpdateConnector(id string, updater func(s storage.Connector) (sto } _, err = tx.Exec(` update connector - set + set type = $1, name = $2, resource_version = $3, From c789c5808e4a7b3a2126b4f62fa7d5c642b827a2 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Mon, 29 Jan 2018 21:10:31 +0000 Subject: [PATCH 20/72] Update conformance --- storage/conformance/conformance.go | 65 +++++++++++++---------------- storage/conformance/transactions.go | 1 - 2 files changed, 28 insertions(+), 38 deletions(-) diff --git a/storage/conformance/conformance.go b/storage/conformance/conformance.go index a1399807..6d2eb751 100644 --- a/storage/conformance/conformance.go +++ b/storage/conformance/conformance.go @@ -91,7 +91,6 @@ func testAuthRequestCRUD(t *testing.T, s storage.Storage) { LoggedIn: true, Expiry: neverExpire, ConnectorID: "ldap", - ConnectorData: []byte(`{"some":"data"}`), Claims: storage.Claims{ UserID: "1", Username: "jane", @@ -123,7 +122,6 @@ func testAuthRequestCRUD(t *testing.T, s storage.Storage) { LoggedIn: true, Expiry: neverExpire, ConnectorID: "ldap", - ConnectorData: []byte(`{"some":"data"}`), Claims: storage.Claims{ UserID: "2", Username: "john", @@ -165,14 +163,13 @@ func testAuthRequestCRUD(t *testing.T, s storage.Storage) { func testAuthCodeCRUD(t *testing.T, s storage.Storage) { a1 := storage.AuthCode{ - ID: storage.NewID(), - ClientID: "client1", - RedirectURI: "https://localhost:80/callback", - Nonce: "foobar", - Scopes: []string{"openid", "email"}, - Expiry: neverExpire, - ConnectorID: "ldap", - ConnectorData: []byte(`{"some":"data"}`), + ID: storage.NewID(), + ClientID: "client1", + RedirectURI: "https://localhost:80/callback", + Nonce: "foobar", + Scopes: []string{"openid", "email"}, + Expiry: neverExpire, + ConnectorID: "ldap", Claims: storage.Claims{ UserID: "1", Username: "jane", @@ -187,14 +184,13 @@ func testAuthCodeCRUD(t *testing.T, s storage.Storage) { } a2 := storage.AuthCode{ - ID: storage.NewID(), - ClientID: "client2", - RedirectURI: "https://localhost:80/callback", - Nonce: "foobar", - Scopes: []string{"openid", "email"}, - Expiry: neverExpire, - ConnectorID: "ldap", - ConnectorData: []byte(`{"some":"data"}`), + ID: storage.NewID(), + ClientID: "client2", + RedirectURI: "https://localhost:80/callback", + Nonce: "foobar", + Scopes: []string{"openid", "email"}, + Expiry: neverExpire, + ConnectorID: "ldap", Claims: storage.Claims{ UserID: "2", Username: "john", @@ -323,7 +319,6 @@ func testRefreshTokenCRUD(t *testing.T, s storage.Storage) { EmailVerified: true, Groups: []string{"a", "b"}, }, - ConnectorData: []byte(`{"some":"data"}`), } if err := s.CreateRefresh(refresh); err != nil { t.Fatalf("create refresh token: %v", err) @@ -377,7 +372,6 @@ func testRefreshTokenCRUD(t *testing.T, s storage.Storage) { EmailVerified: true, Groups: []string{"a", "b"}, }, - ConnectorData: []byte(`{"some":"data"}`), } if err := s.CreateRefresh(refresh2); err != nil { @@ -729,14 +723,13 @@ func testGC(t *testing.T, s storage.Storage) { expiry := time.Now().In(est) c := storage.AuthCode{ - ID: storage.NewID(), - ClientID: "foobar", - RedirectURI: "https://localhost:80/callback", - Nonce: "foobar", - Scopes: []string{"openid", "email"}, - Expiry: expiry, - ConnectorID: "ldap", - ConnectorData: []byte(`{"some":"data"}`), + ID: storage.NewID(), + ClientID: "foobar", + RedirectURI: "https://localhost:80/callback", + Nonce: "foobar", + Scopes: []string{"openid", "email"}, + Expiry: expiry, + ConnectorID: "ldap", Claims: storage.Claims{ UserID: "1", Username: "jane", @@ -788,7 +781,6 @@ func testGC(t *testing.T, s storage.Storage) { LoggedIn: true, Expiry: expiry, ConnectorID: "ldap", - ConnectorData: []byte(`{"some":"data"}`), Claims: storage.Claims{ UserID: "1", Username: "jane", @@ -841,14 +833,13 @@ func testTimezones(t *testing.T, s storage.Storage) { expiry := time.Now().In(est).Round(time.Millisecond) c := storage.AuthCode{ - ID: storage.NewID(), - ClientID: "foobar", - RedirectURI: "https://localhost:80/callback", - Nonce: "foobar", - Scopes: []string{"openid", "email"}, - Expiry: expiry, - ConnectorID: "ldap", - ConnectorData: []byte(`{"some":"data"}`), + ID: storage.NewID(), + ClientID: "foobar", + RedirectURI: "https://localhost:80/callback", + Nonce: "foobar", + Scopes: []string{"openid", "email"}, + Expiry: expiry, + ConnectorID: "ldap", Claims: storage.Claims{ UserID: "1", Username: "jane", diff --git a/storage/conformance/transactions.go b/storage/conformance/transactions.go index dc1be1b6..2eb509e1 100644 --- a/storage/conformance/transactions.go +++ b/storage/conformance/transactions.go @@ -67,7 +67,6 @@ func testAuthRequestConcurrentUpdate(t *testing.T, s storage.Storage) { LoggedIn: true, Expiry: neverExpire, ConnectorID: "ldap", - ConnectorData: []byte(`{"some":"data"}`), Claims: storage.Claims{ UserID: "1", Username: "jane", From c54f1656c72f153e7aefac3795b6a22c973b97d9 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Mon, 29 Jan 2018 21:11:59 +0000 Subject: [PATCH 21/72] Fix ETCD storage backend --- storage/etcd/types.go | 83 +++++++++++++++++++++---------------------- 1 file changed, 40 insertions(+), 43 deletions(-) diff --git a/storage/etcd/types.go b/storage/etcd/types.go index 8063c69f..e9075ed6 100644 --- a/storage/etcd/types.go +++ b/storage/etcd/types.go @@ -16,24 +16,22 @@ type AuthCode struct { Nonce string `json:"nonce,omitempty"` Scopes []string `json:"scopes,omitempty"` - ConnectorID string `json:"connectorID,omitempty"` - ConnectorData []byte `json:"connectorData,omitempty"` - Claims Claims `json:"claims,omitempty"` + ConnectorID string `json:"connectorID,omitempty"` + Claims Claims `json:"claims,omitempty"` Expiry time.Time `json:"expiry"` } func fromStorageAuthCode(a storage.AuthCode) AuthCode { return AuthCode{ - ID: a.ID, - ClientID: a.ClientID, - RedirectURI: a.RedirectURI, - ConnectorID: a.ConnectorID, - ConnectorData: a.ConnectorData, - Nonce: a.Nonce, - Scopes: a.Scopes, - Claims: fromStorageClaims(a.Claims), - Expiry: a.Expiry, + ID: a.ID, + ClientID: a.ClientID, + RedirectURI: a.RedirectURI, + ConnectorID: a.ConnectorID, + Nonce: a.Nonce, + Scopes: a.Scopes, + Claims: fromStorageClaims(a.Claims), + Expiry: a.Expiry, } } @@ -74,7 +72,6 @@ func fromStorageAuthRequest(a storage.AuthRequest) AuthRequest { LoggedIn: a.LoggedIn, Claims: fromStorageClaims(a.Claims), ConnectorID: a.ConnectorID, - ConnectorData: a.ConnectorData, } } @@ -90,7 +87,6 @@ func toStorageAuthRequest(a AuthRequest) storage.AuthRequest { ForceApprovalPrompt: a.ForceApprovalPrompt, LoggedIn: a.LoggedIn, ConnectorID: a.ConnectorID, - ConnectorData: a.ConnectorData, Expiry: a.Expiry, Claims: toStorageClaims(a.Claims), } @@ -118,31 +114,29 @@ type RefreshToken struct { func toStorageRefreshToken(r RefreshToken) storage.RefreshToken { return storage.RefreshToken{ - ID: r.ID, - Token: r.Token, - CreatedAt: r.CreatedAt, - LastUsed: r.LastUsed, - ClientID: r.ClientID, - ConnectorID: r.ConnectorID, - ConnectorData: r.ConnectorData, - Scopes: r.Scopes, - Nonce: r.Nonce, - Claims: toStorageClaims(r.Claims), + ID: r.ID, + Token: r.Token, + CreatedAt: r.CreatedAt, + LastUsed: r.LastUsed, + ClientID: r.ClientID, + ConnectorID: r.ConnectorID, + Scopes: r.Scopes, + Nonce: r.Nonce, + Claims: toStorageClaims(r.Claims), } } func fromStorageRefreshToken(r storage.RefreshToken) RefreshToken { return RefreshToken{ - ID: r.ID, - Token: r.Token, - CreatedAt: r.CreatedAt, - LastUsed: r.LastUsed, - ClientID: r.ClientID, - ConnectorID: r.ConnectorID, - ConnectorData: r.ConnectorData, - Scopes: r.Scopes, - Nonce: r.Nonce, - Claims: fromStorageClaims(r.Claims), + ID: r.ID, + Token: r.Token, + CreatedAt: r.CreatedAt, + LastUsed: r.LastUsed, + ClientID: r.ClientID, + ConnectorID: r.ConnectorID, + Scopes: r.Scopes, + Nonce: r.Nonce, + Claims: fromStorageClaims(r.Claims), } } @@ -188,24 +182,27 @@ type Keys struct { // OfflineSessions is a mirrored struct from storage with JSON struct tags type OfflineSessions struct { - UserID string `json:"user_id,omitempty"` - ConnID string `json:"conn_id,omitempty"` - Refresh map[string]*storage.RefreshTokenRef `json:"refresh,omitempty"` + UserID string `json:"user_id,omitempty"` + ConnID string `json:"conn_id,omitempty"` + Refresh map[string]*storage.RefreshTokenRef `json:"refresh,omitempty"` + ConnectorData []byte `json:"connectorData,omitempty"` } func fromStorageOfflineSessions(o storage.OfflineSessions) OfflineSessions { return OfflineSessions{ - UserID: o.UserID, - ConnID: o.ConnID, - Refresh: o.Refresh, + UserID: o.UserID, + ConnID: o.ConnID, + Refresh: o.Refresh, + ConnectorData: o.ConnectorData, } } func toStorageOfflineSessions(o OfflineSessions) storage.OfflineSessions { s := storage.OfflineSessions{ - UserID: o.UserID, - ConnID: o.ConnID, - Refresh: o.Refresh, + UserID: o.UserID, + ConnID: o.ConnID, + Refresh: o.Refresh, + ConnectorData: o.ConnectorData, } if s.Refresh == nil { // Server code assumes this will be non-nil. From 7a76c767fed725d6567aba31ae08cc0dab0486ea Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Mon, 29 Jan 2018 21:15:01 +0000 Subject: [PATCH 22/72] Update Kubernetes storage backend --- storage/kubernetes/types.go | 94 ++++++++++++++++++------------------- 1 file changed, 45 insertions(+), 49 deletions(-) diff --git a/storage/kubernetes/types.go b/storage/kubernetes/types.go index a42238b3..abc11ba4 100644 --- a/storage/kubernetes/types.go +++ b/storage/kubernetes/types.go @@ -265,8 +265,7 @@ type AuthRequest struct { // with a backend. Claims Claims `json:"claims,omitempty"` // The connector used to login the user. Set when the user authenticates. - ConnectorID string `json:"connectorID,omitempty"` - ConnectorData []byte `json:"connectorData,omitempty"` + ConnectorID string `json:"connectorID,omitempty"` Expiry time.Time `json:"expiry"` } @@ -290,7 +289,6 @@ func toStorageAuthRequest(req AuthRequest) storage.AuthRequest { ForceApprovalPrompt: req.ForceApprovalPrompt, LoggedIn: req.LoggedIn, ConnectorID: req.ConnectorID, - ConnectorData: req.ConnectorData, Expiry: req.Expiry, Claims: toStorageClaims(req.Claims), } @@ -316,7 +314,6 @@ func (cli *client) fromStorageAuthRequest(a storage.AuthRequest) AuthRequest { LoggedIn: a.LoggedIn, ForceApprovalPrompt: a.ForceApprovalPrompt, ConnectorID: a.ConnectorID, - ConnectorData: a.ConnectorData, Expiry: a.Expiry, Claims: fromStorageClaims(a.Claims), } @@ -411,28 +408,26 @@ func (cli *client) fromStorageAuthCode(a storage.AuthCode) AuthCode { Name: a.ID, Namespace: cli.namespace, }, - ClientID: a.ClientID, - RedirectURI: a.RedirectURI, - ConnectorID: a.ConnectorID, - ConnectorData: a.ConnectorData, - Nonce: a.Nonce, - Scopes: a.Scopes, - Claims: fromStorageClaims(a.Claims), - Expiry: a.Expiry, + ClientID: a.ClientID, + RedirectURI: a.RedirectURI, + ConnectorID: a.ConnectorID, + Nonce: a.Nonce, + Scopes: a.Scopes, + Claims: fromStorageClaims(a.Claims), + Expiry: a.Expiry, } } func toStorageAuthCode(a AuthCode) storage.AuthCode { return storage.AuthCode{ - ID: a.ObjectMeta.Name, - ClientID: a.ClientID, - RedirectURI: a.RedirectURI, - ConnectorID: a.ConnectorID, - ConnectorData: a.ConnectorData, - Nonce: a.Nonce, - Scopes: a.Scopes, - Claims: toStorageClaims(a.Claims), - Expiry: a.Expiry, + ID: a.ObjectMeta.Name, + ClientID: a.ClientID, + RedirectURI: a.RedirectURI, + ConnectorID: a.ConnectorID, + Nonce: a.Nonce, + Scopes: a.Scopes, + Claims: toStorageClaims(a.Claims), + Expiry: a.Expiry, } } @@ -466,16 +461,15 @@ type RefreshList struct { func toStorageRefreshToken(r RefreshToken) storage.RefreshToken { return storage.RefreshToken{ - ID: r.ObjectMeta.Name, - Token: r.Token, - CreatedAt: r.CreatedAt, - LastUsed: r.LastUsed, - ClientID: r.ClientID, - ConnectorID: r.ConnectorID, - ConnectorData: r.ConnectorData, - Scopes: r.Scopes, - Nonce: r.Nonce, - Claims: toStorageClaims(r.Claims), + ID: r.ObjectMeta.Name, + Token: r.Token, + CreatedAt: r.CreatedAt, + LastUsed: r.LastUsed, + ClientID: r.ClientID, + ConnectorID: r.ConnectorID, + Scopes: r.Scopes, + Nonce: r.Nonce, + Claims: toStorageClaims(r.Claims), } } @@ -489,15 +483,14 @@ func (cli *client) fromStorageRefreshToken(r storage.RefreshToken) RefreshToken Name: r.ID, Namespace: cli.namespace, }, - Token: r.Token, - CreatedAt: r.CreatedAt, - LastUsed: r.LastUsed, - ClientID: r.ClientID, - ConnectorID: r.ConnectorID, - ConnectorData: r.ConnectorData, - Scopes: r.Scopes, - Nonce: r.Nonce, - Claims: fromStorageClaims(r.Claims), + Token: r.Token, + CreatedAt: r.CreatedAt, + LastUsed: r.LastUsed, + ClientID: r.ClientID, + ConnectorID: r.ConnectorID, + Scopes: r.Scopes, + Nonce: r.Nonce, + Claims: fromStorageClaims(r.Claims), } } @@ -552,9 +545,10 @@ type OfflineSessions struct { k8sapi.TypeMeta `json:",inline"` k8sapi.ObjectMeta `json:"metadata,omitempty"` - UserID string `json:"userID,omitempty"` - ConnID string `json:"connID,omitempty"` - Refresh map[string]*storage.RefreshTokenRef `json:"refresh,omitempty"` + UserID string `json:"userID,omitempty"` + ConnID string `json:"connID,omitempty"` + Refresh map[string]*storage.RefreshTokenRef `json:"refresh,omitempty"` + ConnectorData []byte `json:"connectorData,omitempty"` } func (cli *client) fromStorageOfflineSessions(o storage.OfflineSessions) OfflineSessions { @@ -567,17 +561,19 @@ func (cli *client) fromStorageOfflineSessions(o storage.OfflineSessions) Offline Name: cli.offlineTokenName(o.UserID, o.ConnID), Namespace: cli.namespace, }, - UserID: o.UserID, - ConnID: o.ConnID, - Refresh: o.Refresh, + UserID: o.UserID, + ConnID: o.ConnID, + Refresh: o.Refresh, + ConnectorData: o.ConnectorData, } } func toStorageOfflineSessions(o OfflineSessions) storage.OfflineSessions { s := storage.OfflineSessions{ - UserID: o.UserID, - ConnID: o.ConnID, - Refresh: o.Refresh, + UserID: o.UserID, + ConnID: o.ConnID, + Refresh: o.Refresh, + ConnectorData: o.ConnectorData, } if s.Refresh == nil { // Server code assumes this will be non-nil. From b9b315dd6418070c920d01eb87b366d8681f9a5d Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Tue, 30 Jan 2018 11:18:00 +0000 Subject: [PATCH 23/72] Fix conformance tests --- storage/conformance/conformance.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/storage/conformance/conformance.go b/storage/conformance/conformance.go index 6d2eb751..ea21edae 100644 --- a/storage/conformance/conformance.go +++ b/storage/conformance/conformance.go @@ -509,9 +509,10 @@ func testPasswordCRUD(t *testing.T, s storage.Storage) { func testOfflineSessionCRUD(t *testing.T, s storage.Storage) { userID1 := storage.NewID() session1 := storage.OfflineSessions{ - UserID: userID1, - ConnID: "Conn1", - Refresh: make(map[string]*storage.RefreshTokenRef), + UserID: userID1, + ConnID: "Conn1", + Refresh: make(map[string]*storage.RefreshTokenRef), + ConnectorData: []byte(`{"some":"data"}`), } // Creating an OfflineSession with an empty Refresh list to ensure that @@ -526,9 +527,10 @@ func testOfflineSessionCRUD(t *testing.T, s storage.Storage) { userID2 := storage.NewID() session2 := storage.OfflineSessions{ - UserID: userID2, - ConnID: "Conn2", - Refresh: make(map[string]*storage.RefreshTokenRef), + UserID: userID2, + ConnID: "Conn2", + Refresh: make(map[string]*storage.RefreshTokenRef), + ConnectorData: []byte(`{"some":"data"}`), } if err := s.CreateOfflineSessions(session2); err != nil { From 80995dff9b8a524c342292f179ca5d801af16218 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Tue, 30 Jan 2018 11:19:08 +0000 Subject: [PATCH 24/72] Fix SQL storage --- storage/sql/crud.go | 4 ++-- storage/sql/migrate.go | 24 +++++++++++------------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/storage/sql/crud.go b/storage/sql/crud.go index 26a42176..67cab973 100644 --- a/storage/sql/crud.go +++ b/storage/sql/crud.go @@ -330,7 +330,7 @@ func getRefresh(q querier, id string) (storage.RefreshToken, error) { claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, - connector_id, connector_data, + connector_id, token, created_at, last_used from refresh_token where id = $1; `, id)) @@ -685,7 +685,7 @@ func (c *conn) UpdateOfflineSessions(userID string, connID string, updater func( _, err = tx.Exec(` update offline_session set - refresh = $1 + refresh = $1, connector_data = $2 where user_id = $3 AND conn_id = $4; `, diff --git a/storage/sql/migrate.go b/storage/sql/migrate.go index 0ef62609..bce8e5cf 100644 --- a/storage/sql/migrate.go +++ b/storage/sql/migrate.go @@ -90,18 +90,17 @@ var migrations = []migration{ nonce text not null, state text not null, force_approval_prompt boolean not null, - + logged_in boolean not null, - + claims_user_id text not null, claims_username text not null, claims_email text not null, claims_email_verified boolean not null, claims_groups bytea not null, -- JSON array of strings - + connector_id text not null, - connector_data bytea, - + expiry timestamptz not null );`, ` @@ -111,16 +110,15 @@ var migrations = []migration{ scopes bytea not null, -- JSON array of strings nonce text not null, redirect_uri text not null, - + claims_user_id text not null, claims_username text not null, claims_email text not null, claims_email_verified boolean not null, claims_groups bytea not null, -- JSON array of strings - + connector_id text not null, - connector_data bytea, - + expiry timestamptz not null );`, ` @@ -129,15 +127,14 @@ var migrations = []migration{ client_id text not null, scopes bytea not null, -- JSON array of strings nonce text not null, - + claims_user_id text not null, claims_username text not null, claims_email text not null, claims_email_verified boolean not null, claims_groups bytea not null, -- JSON array of strings - - connector_id text not null, - connector_data bytea + + connector_id text not null );`, ` create table password ( @@ -175,6 +172,7 @@ var migrations = []migration{ user_id text not null, conn_id text not null, refresh bytea not null, + connector_data bytea not null, PRIMARY KEY (user_id, conn_id) );`, }, From 4076eed17b929830a80b43b41c80e24d31cbb1da Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Sun, 4 Feb 2018 17:20:05 +0000 Subject: [PATCH 25/72] Build opts based on scope --- connector/oidc/oidc.go | 9 +++++++-- server/handlers.go | 4 +++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/connector/oidc/oidc.go b/connector/oidc/oidc.go index dfab061a..1a9462da 100644 --- a/connector/oidc/oidc.go +++ b/connector/oidc/oidc.go @@ -168,14 +168,19 @@ func (c *oidcConnector) LoginURL(s connector.Scopes, callbackURL, state string) return "", fmt.Errorf("expected callback URL %q did not match the URL in the config %q", callbackURL, c.redirectURI) } + var opts []oauth2.AuthCodeOption if len(c.hostedDomains) > 0 { preferredDomain := c.hostedDomains[0] if len(c.hostedDomains) > 1 { preferredDomain = "*" } - return c.oauth2Config.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("prompt", "consent"), oauth2.SetAuthURLParam("hd", preferredDomain)), nil + opts = append(opts, oauth2.SetAuthURLParam("hd", preferredDomain)) } - return c.oauth2Config.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("prompt", "consent")), nil + + if s.OfflineAccess { + opts = append(opts, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("prompt", "consent")) + } + return c.oauth2Config.AuthCodeURL(state, opts...), nil } type oauth2Error struct { diff --git a/server/handlers.go b/server/handlers.go index 08bf5d04..a4db71cb 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -527,7 +527,9 @@ func (s *Server) finalizeLogin(identity connector.Identity, authReq storage.Auth } else { // Update existing OfflineSession obj with new RefreshTokenRef. if err := s.storage.UpdateOfflineSessions(session.UserID, session.ConnID, func(old storage.OfflineSessions) (storage.OfflineSessions, error) { - old.ConnectorData = identity.ConnectorData + if len(identity.ConnectorData) > 0 { + old.ConnectorData = identity.ConnectorData + } return old, nil }); err != nil { s.logger.Errorf("failed to update offline session: %v", err) From 433bb2afec0dd9e27baf984fb9a5b99625750aaf Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Mon, 5 Feb 2018 20:58:59 +0000 Subject: [PATCH 26/72] Remove duplicate code --- connector/oidc/oidc.go | 76 +++++++++++------------------------------- 1 file changed, 20 insertions(+), 56 deletions(-) diff --git a/connector/oidc/oidc.go b/connector/oidc/oidc.go index 1a9462da..cdb3ff55 100644 --- a/connector/oidc/oidc.go +++ b/connector/oidc/oidc.go @@ -205,11 +205,29 @@ func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (ide return identity, fmt.Errorf("oidc: failed to get token: %v", err) } + return c.createIdentity(r.Context(), identity, token) +} + +// Refresh is implemented for backwards compatibility, even though it's a no-op. +func (c *oidcConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) { + t := &oauth2.Token{ + RefreshToken: string(identity.ConnectorData), + Expiry: time.Now().Add(-time.Hour), + } + token, err := c.oauth2Config.TokenSource(ctx, t).Token() + if err != nil { + return identity, fmt.Errorf("oidc: failed to get token: %v", err) + } + + return c.createIdentity(ctx, identity, token) +} + +func (c *oidcConnector) createIdentity(ctx context.Context, identity connector.Identity, token *oauth2.Token) (connector.Identity, error) { rawIDToken, ok := token.Extra("id_token").(string) if !ok { return identity, errors.New("oidc: no id_token in token response") } - idToken, err := c.verifier.Verify(r.Context(), rawIDToken) + idToken, err := c.verifier.Verify(ctx, rawIDToken) if err != nil { return identity, fmt.Errorf("oidc: failed to verify ID Token: %v", err) } @@ -221,7 +239,7 @@ func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (ide // We immediately want to run getUserInfo if configured before we validate the claims if c.getUserInfo { - userInfo, err := c.provider.UserInfo(r.Context(), oauth2.StaticTokenSource(token)) + userInfo, err := c.provider.UserInfo(ctx, oauth2.StaticTokenSource(token)) if err != nil { return identity, fmt.Errorf("oidc: error loading userinfo: %v", err) } @@ -284,57 +302,3 @@ func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (ide return identity, nil } - -// Refresh is implemented for backwards compatibility, even though it's a no-op. -func (c *oidcConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) { - t := &oauth2.Token{ - RefreshToken: string(identity.ConnectorData), - Expiry: time.Now().Add(-time.Hour), - } - token, err := c.oauth2Config.TokenSource(ctx, t).Token() - if err != nil { - return identity, fmt.Errorf("oidc: failed to get token: %v", err) - } - - rawIDToken, ok := token.Extra("id_token").(string) - if !ok { - return identity, errors.New("oidc: no id_token in token response") - } - idToken, err := c.verifier.Verify(ctx, rawIDToken) - if err != nil { - return identity, fmt.Errorf("oidc: failed to verify ID Token: %v", err) - } - - var claims struct { - Username string `json:"name"` - Email string `json:"email"` - EmailVerified bool `json:"email_verified"` - HostedDomain string `json:"hd"` - } - if err := idToken.Claims(&claims); err != nil { - return identity, fmt.Errorf("oidc: failed to decode claims: %v", err) - } - - if len(c.hostedDomains) > 0 { - found := false - for _, domain := range c.hostedDomains { - if claims.HostedDomain == domain { - found = true - break - } - } - - if !found { - return identity, fmt.Errorf("oidc: unexpected hd claim %v", claims.HostedDomain) - } - } - - identity = connector.Identity{ - UserID: idToken.Subject, - Username: claims.Username, - Email: claims.Email, - EmailVerified: claims.EmailVerified, - ConnectorData: []byte(token.RefreshToken), - } - return identity, nil -} From d38909831c2f5db10d5552265321e6c642a90212 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Thu, 15 Feb 2018 10:02:03 +0000 Subject: [PATCH 27/72] Fix migration in SQL connector I didn't realise quite what the migration mechanism was. Have understood it now. --- storage/sql/migrate.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/storage/sql/migrate.go b/storage/sql/migrate.go index bce8e5cf..ecf1ae77 100644 --- a/storage/sql/migrate.go +++ b/storage/sql/migrate.go @@ -100,6 +100,7 @@ var migrations = []migration{ claims_groups bytea not null, -- JSON array of strings connector_id text not null, + connector_data bytea, expiry timestamptz not null );`, @@ -118,6 +119,7 @@ var migrations = []migration{ claims_groups bytea not null, -- JSON array of strings connector_id text not null, + connector_data bytea, expiry timestamptz not null );`, @@ -134,7 +136,8 @@ var migrations = []migration{ claims_email_verified boolean not null, claims_groups bytea not null, -- JSON array of strings - connector_id text not null + connector_id text not null, + connector_data bytea );`, ` create table password ( @@ -172,7 +175,6 @@ var migrations = []migration{ user_id text not null, conn_id text not null, refresh bytea not null, - connector_data bytea not null, PRIMARY KEY (user_id, conn_id) );`, }, @@ -200,4 +202,11 @@ var migrations = []migration{ add column claims_preferred_username text not null default '';`, }, }, + { + stmts: []string{` + alter table offline_session + add column connector_data bytea not null default ''; + `, + }, + }, } From fea048b3e873096936bc0bb8ef68a21984aefe26 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Thu, 15 Feb 2018 11:00:06 +0000 Subject: [PATCH 28/72] Fix SQL updater func --- storage/sql/crud.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/storage/sql/crud.go b/storage/sql/crud.go index 67cab973..4e0dffaf 100644 --- a/storage/sql/crud.go +++ b/storage/sql/crud.go @@ -689,7 +689,7 @@ func (c *conn) UpdateOfflineSessions(userID string, connID string, updater func( connector_data = $2 where user_id = $3 AND conn_id = $4; `, - encoder(newSession.Refresh), s.ConnectorData, s.UserID, s.ConnID, + encoder(newSession.Refresh), newSession.ConnectorData, s.UserID, s.ConnID, ) if err != nil { return fmt.Errorf("update offline session: %v", err) From 176ba709a43ebd7a525f5471e830d8cfc554693c Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Thu, 18 Apr 2019 13:52:05 +0100 Subject: [PATCH 29/72] Revert "Remove connectordata from other structs" This reverts commit 27f33516db343bd79b56a47ecef0fe514a35082d. --- server/api_test.go | 1 + server/handlers.go | 37 ++++++++++++++++++++----------------- storage/storage.go | 13 ++++++++----- 3 files changed, 29 insertions(+), 22 deletions(-) diff --git a/server/api_test.go b/server/api_test.go index a7891208..80a22486 100644 --- a/server/api_test.go +++ b/server/api_test.go @@ -259,6 +259,7 @@ func TestRefreshToken(t *testing.T) { EmailVerified: true, Groups: []string{"a", "b"}, }, + ConnectorData: []byte(`{"some":"data"}`), } if err := s.CreateRefresh(r); err != nil { diff --git a/server/handlers.go b/server/handlers.go index a4db71cb..80965daf 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -490,6 +490,7 @@ func (s *Server) finalizeLogin(identity connector.Identity, authReq storage.Auth updater := func(a storage.AuthRequest) (storage.AuthRequest, error) { a.LoggedIn = true a.Claims = claims + a.ConnectorData = identity.ConnectorData return a, nil } if err := s.storage.UpdateAuthRequest(authReq.ID, updater); err != nil { @@ -621,14 +622,15 @@ func (s *Server) sendCodeResponse(w http.ResponseWriter, r *http.Request, authRe switch responseType { case responseTypeCode: code = storage.AuthCode{ - ID: storage.NewID(), - ClientID: authReq.ClientID, - ConnectorID: authReq.ConnectorID, - Nonce: authReq.Nonce, - Scopes: authReq.Scopes, - Claims: authReq.Claims, - Expiry: s.now().Add(time.Minute * 30), - RedirectURI: authReq.RedirectURI, + ID: storage.NewID(), + ClientID: authReq.ClientID, + ConnectorID: authReq.ConnectorID, + Nonce: authReq.Nonce, + Scopes: authReq.Scopes, + Claims: authReq.Claims, + Expiry: s.now().Add(time.Minute * 30), + RedirectURI: authReq.RedirectURI, + ConnectorData: authReq.ConnectorData, } if err := s.storage.CreateAuthCode(code); err != nil { s.logger.Errorf("Failed to create auth code: %v", err) @@ -824,15 +826,16 @@ func (s *Server) handleAuthCode(w http.ResponseWriter, r *http.Request, client s var refreshToken string if reqRefresh { refresh := storage.RefreshToken{ - ID: storage.NewID(), - Token: storage.NewID(), - ClientID: authCode.ClientID, - ConnectorID: authCode.ConnectorID, - Scopes: authCode.Scopes, - Claims: authCode.Claims, - Nonce: authCode.Nonce, - CreatedAt: s.now(), - LastUsed: s.now(), + ID: storage.NewID(), + Token: storage.NewID(), + ClientID: authCode.ClientID, + ConnectorID: authCode.ConnectorID, + Scopes: authCode.Scopes, + Claims: authCode.Claims, + Nonce: authCode.Nonce, + ConnectorData: authCode.ConnectorData, + CreatedAt: s.now(), + LastUsed: s.now(), } token := &internal.RefreshToken{ RefreshId: refresh.ID, diff --git a/storage/storage.go b/storage/storage.go index 85a60965..cb2a7e0c 100644 --- a/storage/storage.go +++ b/storage/storage.go @@ -181,7 +181,8 @@ type AuthRequest struct { // The connector used to login the user and any data the connector wishes to persists. // Set when the user authenticates. - ConnectorID string + ConnectorID string + ConnectorData []byte } // AuthCode represents a code which can be exchanged for an OAuth2 token response. @@ -212,8 +213,9 @@ type AuthCode struct { Scopes []string // Authentication data provided by an upstream source. - ConnectorID string - Claims Claims + ConnectorID string + ConnectorData []byte + Claims Claims Expiry time.Time } @@ -235,8 +237,9 @@ type RefreshToken struct { ClientID string // Authentication data provided by an upstream source. - ConnectorID string - Claims Claims + ConnectorID string + ConnectorData []byte + Claims Claims // Scopes present in the initial request. Refresh requests may specify a set // of scopes different from the initial request when refreshing a token, From 9ce4393156c2f115789e7c6bf65d075511e2c17a Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Thu, 18 Apr 2019 15:03:27 +0100 Subject: [PATCH 30/72] Revert "Update SQL storage backend" --- storage/sql/crud.go | 49 +++++++++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/storage/sql/crud.go b/storage/sql/crud.go index 4e0dffaf..e96a7b12 100644 --- a/storage/sql/crud.go +++ b/storage/sql/crud.go @@ -110,18 +110,18 @@ func (c *conn) CreateAuthRequest(a storage.AuthRequest) error { force_approval_prompt, logged_in, claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, - connector_id, + connector_id, connector_data, expiry ) values ( - $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17 + $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18 ); `, a.ID, a.ClientID, encoder(a.ResponseTypes), encoder(a.Scopes), a.RedirectURI, a.Nonce, a.State, a.ForceApprovalPrompt, a.LoggedIn, a.Claims.UserID, a.Claims.Username, a.Claims.PreferredUsername, a.Claims.Email, a.Claims.EmailVerified, encoder(a.Claims.Groups), - a.ConnectorID, + a.ConnectorID, a.ConnectorData, a.Expiry, ) if err != nil { @@ -152,16 +152,16 @@ func (c *conn) UpdateAuthRequest(id string, updater func(a storage.AuthRequest) claims_user_id = $9, claims_username = $10, claims_preferred_username = $11, claims_email = $12, claims_email_verified = $13, claims_groups = $14, - connector_id = $15, - expiry = $16 - where id = $17; + connector_id = $15, connector_data = $16, + expiry = $17 + where id = $18; `, a.ClientID, encoder(a.ResponseTypes), encoder(a.Scopes), a.RedirectURI, a.Nonce, a.State, a.ForceApprovalPrompt, a.LoggedIn, a.Claims.UserID, a.Claims.Username, a.Claims.PreferredUsername, a.Claims.Email, a.Claims.EmailVerified, encoder(a.Claims.Groups), - a.ConnectorID, + a.ConnectorID, a.ConnectorData, a.Expiry, r.ID, ) if err != nil { @@ -183,7 +183,7 @@ func getAuthRequest(q querier, id string) (a storage.AuthRequest, err error) { force_approval_prompt, logged_in, claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, - connector_id, expiry + connector_id, connector_data, expiry from auth_request where id = $1; `, id).Scan( &a.ID, &a.ClientID, decoder(&a.ResponseTypes), decoder(&a.Scopes), &a.RedirectURI, &a.Nonce, &a.State, @@ -191,7 +191,7 @@ func getAuthRequest(q querier, id string) (a storage.AuthRequest, err error) { &a.Claims.UserID, &a.Claims.Username, &a.Claims.PreferredUsername, &a.Claims.Email, &a.Claims.EmailVerified, decoder(&a.Claims.Groups), - &a.ConnectorID, &a.Expiry, + &a.ConnectorID, &a.ConnectorData, &a.Expiry, ) if err != nil { if err == sql.ErrNoRows { @@ -208,14 +208,14 @@ func (c *conn) CreateAuthCode(a storage.AuthCode) error { id, client_id, scopes, nonce, redirect_uri, claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, - connector_id, + connector_id, connector_data, expiry ) - values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13); + values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14); `, a.ID, a.ClientID, encoder(a.Scopes), a.Nonce, a.RedirectURI, a.Claims.UserID, a.Claims.Username, a.Claims.PreferredUsername, a.Claims.Email, a.Claims.EmailVerified, - encoder(a.Claims.Groups), a.ConnectorID, a.Expiry, + encoder(a.Claims.Groups), a.ConnectorID, a.ConnectorData, a.Expiry, ) if err != nil { @@ -233,13 +233,13 @@ func (c *conn) GetAuthCode(id string) (a storage.AuthCode, err error) { id, client_id, scopes, nonce, redirect_uri, claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, - connector_id, + connector_id, connector_data, expiry from auth_code where id = $1; `, id).Scan( &a.ID, &a.ClientID, decoder(&a.Scopes), &a.Nonce, &a.RedirectURI, &a.Claims.UserID, &a.Claims.Username, &a.Claims.PreferredUsername, &a.Claims.Email, &a.Claims.EmailVerified, - decoder(&a.Claims.Groups), &a.ConnectorID, &a.Expiry, + decoder(&a.Claims.Groups), &a.ConnectorID, &a.ConnectorData, &a.Expiry, ) if err != nil { if err == sql.ErrNoRows { @@ -256,16 +256,16 @@ func (c *conn) CreateRefresh(r storage.RefreshToken) error { id, client_id, scopes, nonce, claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, - connector_id, + connector_id, connector_data, token, created_at, last_used ) - values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14); + values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15); `, r.ID, r.ClientID, encoder(r.Scopes), r.Nonce, r.Claims.UserID, r.Claims.Username, r.Claims.PreferredUsername, r.Claims.Email, r.Claims.EmailVerified, encoder(r.Claims.Groups), - r.ConnectorID, + r.ConnectorID, r.ConnectorData, r.Token, r.CreatedAt, r.LastUsed, ) if err != nil { @@ -299,17 +299,18 @@ func (c *conn) UpdateRefreshToken(id string, updater func(old storage.RefreshTok claims_email_verified = $8, claims_groups = $9, connector_id = $10, - token = $11, - created_at = $12, - last_used = $13 + connector_data = $11, + token = $12, + created_at = $13, + last_used = $14 where - id = $14 + id = $15 `, r.ClientID, encoder(r.Scopes), r.Nonce, r.Claims.UserID, r.Claims.Username, r.Claims.PreferredUsername, r.Claims.Email, r.Claims.EmailVerified, encoder(r.Claims.Groups), - r.ConnectorID, + r.ConnectorID, r.ConnectorData, r.Token, r.CreatedAt, r.LastUsed, id, ) if err != nil { @@ -330,7 +331,7 @@ func getRefresh(q querier, id string) (storage.RefreshToken, error) { claims_user_id, claims_username, claims_preferred_username, claims_email, claims_email_verified, claims_groups, - connector_id, + connector_id, connector_data, token, created_at, last_used from refresh_token where id = $1; `, id)) @@ -369,7 +370,7 @@ func scanRefresh(s scanner) (r storage.RefreshToken, err error) { &r.Claims.UserID, &r.Claims.Username, &r.Claims.PreferredUsername, &r.Claims.Email, &r.Claims.EmailVerified, decoder(&r.Claims.Groups), - &r.ConnectorID, + &r.ConnectorID, &r.ConnectorData, &r.Token, &r.CreatedAt, &r.LastUsed, ) if err != nil { From 41b7c855d0d95b6e941704f0ab07f218927503d3 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Thu, 18 Apr 2019 15:06:48 +0100 Subject: [PATCH 31/72] Revert "Update conformance" This reverts commit 9c7ceabe8aebf6c740c237c5e76c21397179f901. --- storage/conformance/conformance.go | 65 ++++++++++++++++------------- storage/conformance/transactions.go | 1 + 2 files changed, 38 insertions(+), 28 deletions(-) diff --git a/storage/conformance/conformance.go b/storage/conformance/conformance.go index ea21edae..9832a7d8 100644 --- a/storage/conformance/conformance.go +++ b/storage/conformance/conformance.go @@ -91,6 +91,7 @@ func testAuthRequestCRUD(t *testing.T, s storage.Storage) { LoggedIn: true, Expiry: neverExpire, ConnectorID: "ldap", + ConnectorData: []byte(`{"some":"data"}`), Claims: storage.Claims{ UserID: "1", Username: "jane", @@ -122,6 +123,7 @@ func testAuthRequestCRUD(t *testing.T, s storage.Storage) { LoggedIn: true, Expiry: neverExpire, ConnectorID: "ldap", + ConnectorData: []byte(`{"some":"data"}`), Claims: storage.Claims{ UserID: "2", Username: "john", @@ -163,13 +165,14 @@ func testAuthRequestCRUD(t *testing.T, s storage.Storage) { func testAuthCodeCRUD(t *testing.T, s storage.Storage) { a1 := storage.AuthCode{ - ID: storage.NewID(), - ClientID: "client1", - RedirectURI: "https://localhost:80/callback", - Nonce: "foobar", - Scopes: []string{"openid", "email"}, - Expiry: neverExpire, - ConnectorID: "ldap", + ID: storage.NewID(), + ClientID: "client1", + RedirectURI: "https://localhost:80/callback", + Nonce: "foobar", + Scopes: []string{"openid", "email"}, + Expiry: neverExpire, + ConnectorID: "ldap", + ConnectorData: []byte(`{"some":"data"}`), Claims: storage.Claims{ UserID: "1", Username: "jane", @@ -184,13 +187,14 @@ func testAuthCodeCRUD(t *testing.T, s storage.Storage) { } a2 := storage.AuthCode{ - ID: storage.NewID(), - ClientID: "client2", - RedirectURI: "https://localhost:80/callback", - Nonce: "foobar", - Scopes: []string{"openid", "email"}, - Expiry: neverExpire, - ConnectorID: "ldap", + ID: storage.NewID(), + ClientID: "client2", + RedirectURI: "https://localhost:80/callback", + Nonce: "foobar", + Scopes: []string{"openid", "email"}, + Expiry: neverExpire, + ConnectorID: "ldap", + ConnectorData: []byte(`{"some":"data"}`), Claims: storage.Claims{ UserID: "2", Username: "john", @@ -319,6 +323,7 @@ func testRefreshTokenCRUD(t *testing.T, s storage.Storage) { EmailVerified: true, Groups: []string{"a", "b"}, }, + ConnectorData: []byte(`{"some":"data"}`), } if err := s.CreateRefresh(refresh); err != nil { t.Fatalf("create refresh token: %v", err) @@ -372,6 +377,7 @@ func testRefreshTokenCRUD(t *testing.T, s storage.Storage) { EmailVerified: true, Groups: []string{"a", "b"}, }, + ConnectorData: []byte(`{"some":"data"}`), } if err := s.CreateRefresh(refresh2); err != nil { @@ -725,13 +731,14 @@ func testGC(t *testing.T, s storage.Storage) { expiry := time.Now().In(est) c := storage.AuthCode{ - ID: storage.NewID(), - ClientID: "foobar", - RedirectURI: "https://localhost:80/callback", - Nonce: "foobar", - Scopes: []string{"openid", "email"}, - Expiry: expiry, - ConnectorID: "ldap", + ID: storage.NewID(), + ClientID: "foobar", + RedirectURI: "https://localhost:80/callback", + Nonce: "foobar", + Scopes: []string{"openid", "email"}, + Expiry: expiry, + ConnectorID: "ldap", + ConnectorData: []byte(`{"some":"data"}`), Claims: storage.Claims{ UserID: "1", Username: "jane", @@ -783,6 +790,7 @@ func testGC(t *testing.T, s storage.Storage) { LoggedIn: true, Expiry: expiry, ConnectorID: "ldap", + ConnectorData: []byte(`{"some":"data"}`), Claims: storage.Claims{ UserID: "1", Username: "jane", @@ -835,13 +843,14 @@ func testTimezones(t *testing.T, s storage.Storage) { expiry := time.Now().In(est).Round(time.Millisecond) c := storage.AuthCode{ - ID: storage.NewID(), - ClientID: "foobar", - RedirectURI: "https://localhost:80/callback", - Nonce: "foobar", - Scopes: []string{"openid", "email"}, - Expiry: expiry, - ConnectorID: "ldap", + ID: storage.NewID(), + ClientID: "foobar", + RedirectURI: "https://localhost:80/callback", + Nonce: "foobar", + Scopes: []string{"openid", "email"}, + Expiry: expiry, + ConnectorID: "ldap", + ConnectorData: []byte(`{"some":"data"}`), Claims: storage.Claims{ UserID: "1", Username: "jane", diff --git a/storage/conformance/transactions.go b/storage/conformance/transactions.go index 2eb509e1..dc1be1b6 100644 --- a/storage/conformance/transactions.go +++ b/storage/conformance/transactions.go @@ -67,6 +67,7 @@ func testAuthRequestConcurrentUpdate(t *testing.T, s storage.Storage) { LoggedIn: true, Expiry: neverExpire, ConnectorID: "ldap", + ConnectorData: []byte(`{"some":"data"}`), Claims: storage.Claims{ UserID: "1", Username: "jane", From 236b25b68e7448adae06f56fdfee15bf1e08aa4a Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Thu, 18 Apr 2019 15:17:31 +0100 Subject: [PATCH 32/72] Revert "Fix ETCD storage backend" --- storage/etcd/types.go | 62 ++++++++++++++++++++++++------------------- 1 file changed, 34 insertions(+), 28 deletions(-) diff --git a/storage/etcd/types.go b/storage/etcd/types.go index e9075ed6..a16eae8e 100644 --- a/storage/etcd/types.go +++ b/storage/etcd/types.go @@ -16,22 +16,24 @@ type AuthCode struct { Nonce string `json:"nonce,omitempty"` Scopes []string `json:"scopes,omitempty"` - ConnectorID string `json:"connectorID,omitempty"` - Claims Claims `json:"claims,omitempty"` + ConnectorID string `json:"connectorID,omitempty"` + ConnectorData []byte `json:"connectorData,omitempty"` + Claims Claims `json:"claims,omitempty"` Expiry time.Time `json:"expiry"` } func fromStorageAuthCode(a storage.AuthCode) AuthCode { return AuthCode{ - ID: a.ID, - ClientID: a.ClientID, - RedirectURI: a.RedirectURI, - ConnectorID: a.ConnectorID, - Nonce: a.Nonce, - Scopes: a.Scopes, - Claims: fromStorageClaims(a.Claims), - Expiry: a.Expiry, + ID: a.ID, + ClientID: a.ClientID, + RedirectURI: a.RedirectURI, + ConnectorID: a.ConnectorID, + ConnectorData: a.ConnectorData, + Nonce: a.Nonce, + Scopes: a.Scopes, + Claims: fromStorageClaims(a.Claims), + Expiry: a.Expiry, } } @@ -72,6 +74,7 @@ func fromStorageAuthRequest(a storage.AuthRequest) AuthRequest { LoggedIn: a.LoggedIn, Claims: fromStorageClaims(a.Claims), ConnectorID: a.ConnectorID, + ConnectorData: a.ConnectorData, } } @@ -87,6 +90,7 @@ func toStorageAuthRequest(a AuthRequest) storage.AuthRequest { ForceApprovalPrompt: a.ForceApprovalPrompt, LoggedIn: a.LoggedIn, ConnectorID: a.ConnectorID, + ConnectorData: a.ConnectorData, Expiry: a.Expiry, Claims: toStorageClaims(a.Claims), } @@ -114,29 +118,31 @@ type RefreshToken struct { func toStorageRefreshToken(r RefreshToken) storage.RefreshToken { return storage.RefreshToken{ - ID: r.ID, - Token: r.Token, - CreatedAt: r.CreatedAt, - LastUsed: r.LastUsed, - ClientID: r.ClientID, - ConnectorID: r.ConnectorID, - Scopes: r.Scopes, - Nonce: r.Nonce, - Claims: toStorageClaims(r.Claims), + ID: r.ID, + Token: r.Token, + CreatedAt: r.CreatedAt, + LastUsed: r.LastUsed, + ClientID: r.ClientID, + ConnectorID: r.ConnectorID, + ConnectorData: r.ConnectorData, + Scopes: r.Scopes, + Nonce: r.Nonce, + Claims: toStorageClaims(r.Claims), } } func fromStorageRefreshToken(r storage.RefreshToken) RefreshToken { return RefreshToken{ - ID: r.ID, - Token: r.Token, - CreatedAt: r.CreatedAt, - LastUsed: r.LastUsed, - ClientID: r.ClientID, - ConnectorID: r.ConnectorID, - Scopes: r.Scopes, - Nonce: r.Nonce, - Claims: fromStorageClaims(r.Claims), + ID: r.ID, + Token: r.Token, + CreatedAt: r.CreatedAt, + LastUsed: r.LastUsed, + ClientID: r.ClientID, + ConnectorID: r.ConnectorID, + ConnectorData: r.ConnectorData, + Scopes: r.Scopes, + Nonce: r.Nonce, + Claims: fromStorageClaims(r.Claims), } } From 45a40a13a314152f6083e6270b575ea676762720 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Thu, 18 Apr 2019 15:18:50 +0100 Subject: [PATCH 33/72] Revert "Update Kubernetes storage backend" This reverts commit 228bdc324877bf67ecdd434503b9c1b25d8e7d28. --- storage/kubernetes/types.go | 73 ++++++++++++++++++++----------------- 1 file changed, 40 insertions(+), 33 deletions(-) diff --git a/storage/kubernetes/types.go b/storage/kubernetes/types.go index abc11ba4..5eda1781 100644 --- a/storage/kubernetes/types.go +++ b/storage/kubernetes/types.go @@ -265,7 +265,8 @@ type AuthRequest struct { // with a backend. Claims Claims `json:"claims,omitempty"` // The connector used to login the user. Set when the user authenticates. - ConnectorID string `json:"connectorID,omitempty"` + ConnectorID string `json:"connectorID,omitempty"` + ConnectorData []byte `json:"connectorData,omitempty"` Expiry time.Time `json:"expiry"` } @@ -289,6 +290,7 @@ func toStorageAuthRequest(req AuthRequest) storage.AuthRequest { ForceApprovalPrompt: req.ForceApprovalPrompt, LoggedIn: req.LoggedIn, ConnectorID: req.ConnectorID, + ConnectorData: req.ConnectorData, Expiry: req.Expiry, Claims: toStorageClaims(req.Claims), } @@ -314,6 +316,7 @@ func (cli *client) fromStorageAuthRequest(a storage.AuthRequest) AuthRequest { LoggedIn: a.LoggedIn, ForceApprovalPrompt: a.ForceApprovalPrompt, ConnectorID: a.ConnectorID, + ConnectorData: a.ConnectorData, Expiry: a.Expiry, Claims: fromStorageClaims(a.Claims), } @@ -408,26 +411,28 @@ func (cli *client) fromStorageAuthCode(a storage.AuthCode) AuthCode { Name: a.ID, Namespace: cli.namespace, }, - ClientID: a.ClientID, - RedirectURI: a.RedirectURI, - ConnectorID: a.ConnectorID, - Nonce: a.Nonce, - Scopes: a.Scopes, - Claims: fromStorageClaims(a.Claims), - Expiry: a.Expiry, + ClientID: a.ClientID, + RedirectURI: a.RedirectURI, + ConnectorID: a.ConnectorID, + ConnectorData: a.ConnectorData, + Nonce: a.Nonce, + Scopes: a.Scopes, + Claims: fromStorageClaims(a.Claims), + Expiry: a.Expiry, } } func toStorageAuthCode(a AuthCode) storage.AuthCode { return storage.AuthCode{ - ID: a.ObjectMeta.Name, - ClientID: a.ClientID, - RedirectURI: a.RedirectURI, - ConnectorID: a.ConnectorID, - Nonce: a.Nonce, - Scopes: a.Scopes, - Claims: toStorageClaims(a.Claims), - Expiry: a.Expiry, + ID: a.ObjectMeta.Name, + ClientID: a.ClientID, + RedirectURI: a.RedirectURI, + ConnectorID: a.ConnectorID, + ConnectorData: a.ConnectorData, + Nonce: a.Nonce, + Scopes: a.Scopes, + Claims: toStorageClaims(a.Claims), + Expiry: a.Expiry, } } @@ -461,15 +466,16 @@ type RefreshList struct { func toStorageRefreshToken(r RefreshToken) storage.RefreshToken { return storage.RefreshToken{ - ID: r.ObjectMeta.Name, - Token: r.Token, - CreatedAt: r.CreatedAt, - LastUsed: r.LastUsed, - ClientID: r.ClientID, - ConnectorID: r.ConnectorID, - Scopes: r.Scopes, - Nonce: r.Nonce, - Claims: toStorageClaims(r.Claims), + ID: r.ObjectMeta.Name, + Token: r.Token, + CreatedAt: r.CreatedAt, + LastUsed: r.LastUsed, + ClientID: r.ClientID, + ConnectorID: r.ConnectorID, + ConnectorData: r.ConnectorData, + Scopes: r.Scopes, + Nonce: r.Nonce, + Claims: toStorageClaims(r.Claims), } } @@ -483,14 +489,15 @@ func (cli *client) fromStorageRefreshToken(r storage.RefreshToken) RefreshToken Name: r.ID, Namespace: cli.namespace, }, - Token: r.Token, - CreatedAt: r.CreatedAt, - LastUsed: r.LastUsed, - ClientID: r.ClientID, - ConnectorID: r.ConnectorID, - Scopes: r.Scopes, - Nonce: r.Nonce, - Claims: fromStorageClaims(r.Claims), + Token: r.Token, + CreatedAt: r.CreatedAt, + LastUsed: r.LastUsed, + ClientID: r.ClientID, + ConnectorID: r.ConnectorID, + ConnectorData: r.ConnectorData, + Scopes: r.Scopes, + Nonce: r.Nonce, + Claims: fromStorageClaims(r.Claims), } } From 19ad7daa7f71aaf062dd4f05a15034eed916e11c Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Tue, 23 Apr 2019 10:59:36 +0100 Subject: [PATCH 34/72] Use old ConnectorData before session.ConnectorData --- server/handlers.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/server/handlers.go b/server/handlers.go index 80965daf..35164717 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -1003,6 +1003,9 @@ func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, clie s.logger.Errorf("failed to get offline session: %v", err) return } + } else if len(refresh.ConnectorData) > 0 { + // Use the old connector data if it exists, should be deleted once used + connectorData = session.ConnectorData } else { connectorData = session.ConnectorData } @@ -1087,6 +1090,9 @@ func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, clie old.Claims.EmailVerified = ident.EmailVerified old.Claims.Groups = ident.Groups old.LastUsed = lastUsed + + // ConnectorData has been moved to OfflineSession + old.ConnectorData = []byte{} return old, nil } From 8b344fe4d3cd329643e50f1e33d2342bc723c83d Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Fri, 10 May 2019 15:31:50 +0100 Subject: [PATCH 35/72] Fix Refresh comment --- connector/oidc/oidc.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/connector/oidc/oidc.go b/connector/oidc/oidc.go index cdb3ff55..0abc0bc4 100644 --- a/connector/oidc/oidc.go +++ b/connector/oidc/oidc.go @@ -208,7 +208,7 @@ func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (ide return c.createIdentity(r.Context(), identity, token) } -// Refresh is implemented for backwards compatibility, even though it's a no-op. +// Refresh is used to refresh a session with the refresh token provided by the IdP func (c *oidcConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) { t := &oauth2.Token{ RefreshToken: string(identity.ConnectorData), From f6077083c91ae9b99ebef99eb2bf56e345313557 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Wed, 25 Sep 2019 21:12:20 +0100 Subject: [PATCH 36/72] Identify error as failure to retrieve refresh token --- connector/oidc/oidc.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/connector/oidc/oidc.go b/connector/oidc/oidc.go index 0abc0bc4..df849093 100644 --- a/connector/oidc/oidc.go +++ b/connector/oidc/oidc.go @@ -216,7 +216,7 @@ func (c *oidcConnector) Refresh(ctx context.Context, s connector.Scopes, identit } token, err := c.oauth2Config.TokenSource(ctx, t).Token() if err != nil { - return identity, fmt.Errorf("oidc: failed to get token: %v", err) + return identity, fmt.Errorf("oidc: failed to get refresh token: %v", err) } return c.createIdentity(ctx, identity, token) From 77fcf9ad77e02859f57b979556a9766dcc63bc61 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Wed, 25 Sep 2019 21:20:19 +0100 Subject: [PATCH 37/72] Use a struct for connector data within OIDC connector --- connector/oidc/oidc.go | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/connector/oidc/oidc.go b/connector/oidc/oidc.go index df849093..749b56ed 100644 --- a/connector/oidc/oidc.go +++ b/connector/oidc/oidc.go @@ -3,6 +3,7 @@ package oidc import ( "context" + "encoding/json" "errors" "fmt" "net/http" @@ -61,6 +62,11 @@ var brokenAuthHeaderDomains = []string{ "oktapreview.com", } +// connectorData stores information for sessions authenticated by this connector +type connectorData struct { + refreshToken []byte +} + // Detect auth header provider issues for known providers. This lets users // avoid having to explicitly set "basicAuthUnsupported" in their config. // @@ -210,8 +216,14 @@ func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (ide // Refresh is used to refresh a session with the refresh token provided by the IdP func (c *oidcConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) { + cd := connectorData{} + err := json.Unmarshal(identity.ConnectorData, &cd) + if err != nil { + return identity, fmt.Errorf("oidc: failed to unmarshal connector data: %v", err) + } + t := &oauth2.Token{ - RefreshToken: string(identity.ConnectorData), + RefreshToken: string(cd.refreshToken), Expiry: time.Now().Add(-time.Hour), } token, err := c.oauth2Config.TokenSource(ctx, t).Token() @@ -284,12 +296,21 @@ func (c *oidcConnector) createIdentity(ctx context.Context, identity connector.I } } + cd := connectorData{ + refreshToken: []byte(token.RefreshToken), + } + + connData, err := json.Marshal(&cd) + if err != nil { + return identity, fmt.Errorf("oidc: failed to encode connector data: %v", err) + } + identity = connector.Identity{ UserID: idToken.Subject, Username: name, Email: email, EmailVerified: emailVerified, - ConnectorData: []byte(token.RefreshToken), + ConnectorData: connData, } if c.userIDKey != "" { From d9095073c80d0d585c93efb764bf4594c62b4656 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Wed, 25 Sep 2019 21:27:31 +0100 Subject: [PATCH 38/72] Unindent session updates on finalizeLogin --- server/handlers.go | 65 ++++++++++++++++++++++++---------------------- 1 file changed, 34 insertions(+), 31 deletions(-) diff --git a/server/handlers.go b/server/handlers.go index 35164717..49116b88 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -505,42 +505,45 @@ func (s *Server) finalizeLogin(identity connector.Identity, authReq storage.Auth s.logger.Infof("login successful: connector %q, username=%q, preferred_username=%q, email=%q, groups=%q", authReq.ConnectorID, claims.Username, claims.PreferredUsername, email, claims.Groups) - if _, ok := conn.(connector.RefreshConnector); ok { - // Try to retrieve an existing OfflineSession object for the corresponding user. - if session, err := s.storage.GetOfflineSessions(identity.UserID, authReq.ConnectorID); err != nil { - if err != storage.ErrNotFound { - s.logger.Errorf("failed to get offline session: %v", err) - return "", err - } - offlineSessions := storage.OfflineSessions{ - UserID: identity.UserID, - ConnID: authReq.ConnectorID, - Refresh: make(map[string]*storage.RefreshTokenRef), - ConnectorData: identity.ConnectorData, - } + returnURL := path.Join(s.issuerURL.Path, "/approval") + "?req=" + authReq.ID + _, ok := conn.(connector.RefreshConnector) + if !ok { + return returnURL, nil + } - // Create a new OfflineSession object for the user and add a reference object for - // the newly received refreshtoken. - if err := s.storage.CreateOfflineSessions(offlineSessions); err != nil { - s.logger.Errorf("failed to create offline session: %v", err) - return "", err - } - } else { - // Update existing OfflineSession obj with new RefreshTokenRef. - if err := s.storage.UpdateOfflineSessions(session.UserID, session.ConnID, func(old storage.OfflineSessions) (storage.OfflineSessions, error) { - if len(identity.ConnectorData) > 0 { - old.ConnectorData = identity.ConnectorData - } - return old, nil - }); err != nil { - s.logger.Errorf("failed to update offline session: %v", err) - return "", err - } + // Try to retrieve an existing OfflineSession object for the corresponding user. + if session, err := s.storage.GetOfflineSessions(identity.UserID, authReq.ConnectorID); err != nil { + if err != storage.ErrNotFound { + s.logger.Errorf("failed to get offline session: %v", err) + return "", err + } + offlineSessions := storage.OfflineSessions{ + UserID: identity.UserID, + ConnID: authReq.ConnectorID, + Refresh: make(map[string]*storage.RefreshTokenRef), + ConnectorData: identity.ConnectorData, + } + // Create a new OfflineSession object for the user and add a reference object for + // the newly received refreshtoken. + if err := s.storage.CreateOfflineSessions(offlineSessions); err != nil { + s.logger.Errorf("failed to create offline session: %v", err) + return "", err + } + } else { + // Update existing OfflineSession obj with new RefreshTokenRef. + if err := s.storage.UpdateOfflineSessions(session.UserID, session.ConnID, func(old storage.OfflineSessions) (storage.OfflineSessions, error) { + if len(identity.ConnectorData) > 0 { + old.ConnectorData = identity.ConnectorData + } + return old, nil + }); err != nil { + s.logger.Errorf("failed to update offline session: %v", err) + return "", err } } - return path.Join(s.issuerURL.Path, "/approval") + "?req=" + authReq.ID, nil + return returnURL, nil } func (s *Server) handleApproval(w http.ResponseWriter, r *http.Request) { From c4e96dda325bf5906faf7d37acae4aacc59339be Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Wed, 25 Sep 2019 21:31:04 +0100 Subject: [PATCH 39/72] Fix migration of old connector data --- server/handlers.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/handlers.go b/server/handlers.go index 49116b88..0f5b0d23 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -1008,7 +1008,7 @@ func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, clie } } else if len(refresh.ConnectorData) > 0 { // Use the old connector data if it exists, should be deleted once used - connectorData = session.ConnectorData + connectorData = refresh.ConnectorData } else { connectorData = session.ConnectorData } From c782ac809c3f907046c80338f55083576c079e42 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Thu, 26 Sep 2019 15:30:44 +0100 Subject: [PATCH 40/72] Remove defaulting from connector_data column --- storage/sql/migrate.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/storage/sql/migrate.go b/storage/sql/migrate.go index ecf1ae77..5b86bc78 100644 --- a/storage/sql/migrate.go +++ b/storage/sql/migrate.go @@ -205,7 +205,7 @@ var migrations = []migration{ { stmts: []string{` alter table offline_session - add column connector_data bytea not null default ''; + add column connector_data bytea; `, }, }, From 3156553843492c803d5dde1e3ae8d2f1d0350f3d Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Wed, 2 Oct 2019 13:39:52 +0100 Subject: [PATCH 41/72] OIDC: Rename refreshToken to RefreshToken --- connector/oidc/oidc.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/connector/oidc/oidc.go b/connector/oidc/oidc.go index 749b56ed..3e405d87 100644 --- a/connector/oidc/oidc.go +++ b/connector/oidc/oidc.go @@ -64,7 +64,7 @@ var brokenAuthHeaderDomains = []string{ // connectorData stores information for sessions authenticated by this connector type connectorData struct { - refreshToken []byte + RefreshToken []byte } // Detect auth header provider issues for known providers. This lets users @@ -223,7 +223,7 @@ func (c *oidcConnector) Refresh(ctx context.Context, s connector.Scopes, identit } t := &oauth2.Token{ - RefreshToken: string(cd.refreshToken), + RefreshToken: string(cd.RefreshToken), Expiry: time.Now().Add(-time.Hour), } token, err := c.oauth2Config.TokenSource(ctx, t).Token() @@ -297,7 +297,7 @@ func (c *oidcConnector) createIdentity(ctx context.Context, identity connector.I } cd := connectorData{ - refreshToken: []byte(token.RefreshToken), + RefreshToken: []byte(token.RefreshToken), } connData, err := json.Marshal(&cd) From 97ffa21262d0b9aa418919cb90874d4fc71cc4e3 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Sat, 3 Feb 2018 11:52:46 +0000 Subject: [PATCH 42/72] Create separate Google connector --- connector/google/google.go | 190 +++++++++++++++++++++++++++++++++++++ server/server.go | 2 + 2 files changed, 192 insertions(+) create mode 100644 connector/google/google.go diff --git a/connector/google/google.go b/connector/google/google.go new file mode 100644 index 00000000..e0cb4999 --- /dev/null +++ b/connector/google/google.go @@ -0,0 +1,190 @@ +// Package google implements logging in through Google's OpenID Connect provider. +package google + +import ( + "context" + "errors" + "fmt" + "net/http" + "time" + + "github.com/coreos/go-oidc" + "github.com/sirupsen/logrus" + "golang.org/x/oauth2" + + "github.com/dexidp/dex/connector" +) + +// Config holds configuration options for OpenID Connect logins. +type Config struct { + Issuer string `json:"issuer"` + ClientID string `json:"clientID"` + ClientSecret string `json:"clientSecret"` + RedirectURI string `json:"redirectURI"` + + Scopes []string `json:"scopes"` // defaults to "profile" and "email" + + // Optional list of whitelisted domains + // If this field is nonempty, only users from a listed domain will be allowed to log in + HostedDomains []string `json:"hostedDomains"` +} + +// Open returns a connector which can be used to login users through an upstream +// OpenID Connect provider. +func (c *Config) Open(id string, logger logrus.FieldLogger) (conn connector.Connector, err error) { + ctx, cancel := context.WithCancel(context.Background()) + + provider, err := oidc.NewProvider(ctx, c.Issuer) + if err != nil { + cancel() + return nil, fmt.Errorf("failed to get provider: %v", err) + } + + scopes := []string{oidc.ScopeOpenID} + if len(c.Scopes) > 0 { + scopes = append(scopes, c.Scopes...) + } else { + scopes = append(scopes, "profile", "email") + } + + clientID := c.ClientID + return &googleConnector{ + redirectURI: c.RedirectURI, + oauth2Config: &oauth2.Config{ + ClientID: clientID, + ClientSecret: c.ClientSecret, + Endpoint: provider.Endpoint(), + Scopes: scopes, + RedirectURL: c.RedirectURI, + }, + verifier: provider.Verifier( + &oidc.Config{ClientID: clientID}, + ), + logger: logger, + cancel: cancel, + hostedDomains: c.HostedDomains, + }, nil +} + +var ( + _ connector.CallbackConnector = (*googleConnector)(nil) + _ connector.RefreshConnector = (*googleConnector)(nil) +) + +type googleConnector struct { + redirectURI string + oauth2Config *oauth2.Config + verifier *oidc.IDTokenVerifier + ctx context.Context + cancel context.CancelFunc + logger logrus.FieldLogger + hostedDomains []string +} + +func (c *googleConnector) Close() error { + c.cancel() + return nil +} + +func (c *googleConnector) LoginURL(s connector.Scopes, callbackURL, state string) (string, error) { + if c.redirectURI != callbackURL { + return "", fmt.Errorf("expected callback URL %q did not match the URL in the config %q", callbackURL, c.redirectURI) + } + + var opts []oauth2.AuthCodeOption + if len(c.hostedDomains) > 0 { + preferredDomain := c.hostedDomains[0] + if len(c.hostedDomains) > 1 { + preferredDomain = "*" + } + opts = append(opts, oauth2.SetAuthURLParam("hd", preferredDomain)) + } + + if s.OfflineAccess { + opts = append(opts, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("prompt", "consent")) + } + return c.oauth2Config.AuthCodeURL(state, opts...), nil +} + +type oauth2Error struct { + error string + errorDescription string +} + +func (e *oauth2Error) Error() string { + if e.errorDescription == "" { + return e.error + } + return e.error + ": " + e.errorDescription +} + +func (c *googleConnector) HandleCallback(s connector.Scopes, r *http.Request) (identity connector.Identity, err error) { + q := r.URL.Query() + if errType := q.Get("error"); errType != "" { + return identity, &oauth2Error{errType, q.Get("error_description")} + } + token, err := c.oauth2Config.Exchange(r.Context(), q.Get("code")) + if err != nil { + return identity, fmt.Errorf("google: failed to get token: %v", err) + } + + return c.createIdentity(r.Context(), identity, token) +} + +// Refresh is implemented for backwards compatibility, even though it's a no-op. +func (c *googleConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) { + t := &oauth2.Token{ + RefreshToken: string(identity.ConnectorData), + Expiry: time.Now().Add(-time.Hour), + } + token, err := c.oauth2Config.TokenSource(ctx, t).Token() + if err != nil { + return identity, fmt.Errorf("google: failed to get token: %v", err) + } + + return c.createIdentity(ctx, identity, token) +} + +func (c *googleConnector) createIdentity(ctx context.Context, identity connector.Identity, token *oauth2.Token) (connector.Identity, error) { + rawIDToken, ok := token.Extra("id_token").(string) + if !ok { + return identity, errors.New("google: no id_token in token response") + } + idToken, err := c.verifier.Verify(ctx, rawIDToken) + if err != nil { + return identity, fmt.Errorf("google: failed to verify ID Token: %v", err) + } + + var claims struct { + Username string `json:"name"` + Email string `json:"email"` + EmailVerified bool `json:"email_verified"` + HostedDomain string `json:"hd"` + } + if err := idToken.Claims(&claims); err != nil { + return identity, fmt.Errorf("oidc: failed to decode claims: %v", err) + } + + if len(c.hostedDomains) > 0 { + found := false + for _, domain := range c.hostedDomains { + if claims.HostedDomain == domain { + found = true + break + } + } + + if !found { + return identity, fmt.Errorf("oidc: unexpected hd claim %v", claims.HostedDomain) + } + } + + identity = connector.Identity{ + UserID: idToken.Subject, + Username: claims.Username, + Email: claims.Email, + EmailVerified: claims.EmailVerified, + ConnectorData: []byte(token.RefreshToken), + } + return identity, nil +} diff --git a/server/server.go b/server/server.go index 3b722181..fa860330 100644 --- a/server/server.go +++ b/server/server.go @@ -21,6 +21,7 @@ import ( "github.com/dexidp/dex/connector/bitbucketcloud" "github.com/dexidp/dex/connector/github" "github.com/dexidp/dex/connector/gitlab" + "github.com/dexidp/dex/connector/google" "github.com/dexidp/dex/connector/keystone" "github.com/dexidp/dex/connector/ldap" "github.com/dexidp/dex/connector/linkedin" @@ -453,6 +454,7 @@ var ConnectorsConfig = map[string]func() ConnectorConfig{ "ldap": func() ConnectorConfig { return new(ldap.Config) }, "github": func() ConnectorConfig { return new(github.Config) }, "gitlab": func() ConnectorConfig { return new(gitlab.Config) }, + "google": func() ConnectorConfig { return new(google.Config) }, "oidc": func() ConnectorConfig { return new(oidc.Config) }, "saml": func() ConnectorConfig { return new(saml.Config) }, "authproxy": func() ConnectorConfig { return new(authproxy.Config) }, From 36370f8f2a9993902b6d27c9c778917862a4d037 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Sat, 3 Feb 2018 11:53:42 +0000 Subject: [PATCH 43/72] No need to configure issuer --- connector/google/google.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/connector/google/google.go b/connector/google/google.go index e0cb4999..d69bb83e 100644 --- a/connector/google/google.go +++ b/connector/google/google.go @@ -15,9 +15,12 @@ import ( "github.com/dexidp/dex/connector" ) +const ( + issuerURL = "https://accounts.google.com" +) + // Config holds configuration options for OpenID Connect logins. type Config struct { - Issuer string `json:"issuer"` ClientID string `json:"clientID"` ClientSecret string `json:"clientSecret"` RedirectURI string `json:"redirectURI"` @@ -34,7 +37,7 @@ type Config struct { func (c *Config) Open(id string, logger logrus.FieldLogger) (conn connector.Connector, err error) { ctx, cancel := context.WithCancel(context.Background()) - provider, err := oidc.NewProvider(ctx, c.Issuer) + provider, err := oidc.NewProvider(ctx, issuerURL) if err != nil { cancel() return nil, fmt.Errorf("failed to get provider: %v", err) From 3f55e2da72c9ba248ebead33b8c0d71155387980 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Sun, 4 Feb 2018 17:17:17 +0000 Subject: [PATCH 44/72] Get groups from directory api --- connector/google/google.go | 98 ++++++++++++++++++++++++++++++++------ 1 file changed, 83 insertions(+), 15 deletions(-) diff --git a/connector/google/google.go b/connector/google/google.go index d69bb83e..0bfe1290 100644 --- a/connector/google/google.go +++ b/connector/google/google.go @@ -5,14 +5,17 @@ import ( "context" "errors" "fmt" + "io/ioutil" "net/http" "time" "github.com/coreos/go-oidc" - "github.com/sirupsen/logrus" "golang.org/x/oauth2" "github.com/dexidp/dex/connector" + "github.com/dexidp/dex/pkg/log" + "golang.org/x/oauth2/google" + "google.golang.org/api/admin/directory/v1" ) const ( @@ -30,11 +33,21 @@ type Config struct { // Optional list of whitelisted domains // If this field is nonempty, only users from a listed domain will be allowed to log in HostedDomains []string `json:"hostedDomains"` + + // Optional path to service account json + // If nonempty, and groups claim is made, will use authentication from file to + // check groups with the admin directory api + ServiceAccountFilePath string `json:"serviceAccountFilePath"` + + // Required if ServiceAccountFilePath + // The email of a GSuite super user which the service account will impersonate + // when listing groups + AdminEmail string } // Open returns a connector which can be used to login users through an upstream // OpenID Connect provider. -func (c *Config) Open(id string, logger logrus.FieldLogger) (conn connector.Connector, err error) { +func (c *Config) Open(id string, logger log.Logger) (conn connector.Connector, err error) { ctx, cancel := context.WithCancel(context.Background()) provider, err := oidc.NewProvider(ctx, issuerURL) @@ -63,9 +76,11 @@ func (c *Config) Open(id string, logger logrus.FieldLogger) (conn connector.Conn verifier: provider.Verifier( &oidc.Config{ClientID: clientID}, ), - logger: logger, - cancel: cancel, - hostedDomains: c.HostedDomains, + logger: logger, + cancel: cancel, + hostedDomains: c.HostedDomains, + serviceAccountFilePath: c.ServiceAccountFilePath, + adminEmail: c.AdminEmail, }, nil } @@ -75,13 +90,15 @@ var ( ) type googleConnector struct { - redirectURI string - oauth2Config *oauth2.Config - verifier *oidc.IDTokenVerifier - ctx context.Context - cancel context.CancelFunc - logger logrus.FieldLogger - hostedDomains []string + redirectURI string + oauth2Config *oauth2.Config + verifier *oidc.IDTokenVerifier + ctx context.Context + cancel context.CancelFunc + logger log.Logger + hostedDomains []string + serviceAccountFilePath string + adminEmail string } func (c *googleConnector) Close() error { @@ -131,7 +148,7 @@ func (c *googleConnector) HandleCallback(s connector.Scopes, r *http.Request) (i return identity, fmt.Errorf("google: failed to get token: %v", err) } - return c.createIdentity(r.Context(), identity, token) + return c.createIdentity(r.Context(), identity, s, token) } // Refresh is implemented for backwards compatibility, even though it's a no-op. @@ -145,10 +162,10 @@ func (c *googleConnector) Refresh(ctx context.Context, s connector.Scopes, ident return identity, fmt.Errorf("google: failed to get token: %v", err) } - return c.createIdentity(ctx, identity, token) + return c.createIdentity(ctx, identity, s, token) } -func (c *googleConnector) createIdentity(ctx context.Context, identity connector.Identity, token *oauth2.Token) (connector.Identity, error) { +func (c *googleConnector) createIdentity(ctx context.Context, identity connector.Identity, s connector.Scopes, token *oauth2.Token) (connector.Identity, error) { rawIDToken, ok := token.Extra("id_token").(string) if !ok { return identity, errors.New("google: no id_token in token response") @@ -182,12 +199,63 @@ func (c *googleConnector) createIdentity(ctx context.Context, identity connector } } + var groups []string + if s.Groups { + groups, err = c.getGroups(claims.Email) + if err != nil { + return identity, fmt.Errorf("google: could not retrieve groups: %v", err) + } + } + identity = connector.Identity{ UserID: idToken.Subject, Username: claims.Username, Email: claims.Email, EmailVerified: claims.EmailVerified, ConnectorData: []byte(token.RefreshToken), + Groups: groups, } return identity, nil } + +func (c *googleConnector) getGroups(email string) ([]string, error) { + srv, err := createDirectoryService(c.serviceAccountFilePath, c.adminEmail) + if err != nil { + return nil, fmt.Errorf("could not create directory service: %v", err) + } + + groupsList, err := srv.Groups.List().UserKey(email).Do() + if err != nil { + return nil, fmt.Errorf("could not list groups: %v", err) + } + + var userGroups []string + for _, group := range groupsList.Groups { + userGroups = append(userGroups, group.Email) + } + + return userGroups, nil +} + +func createDirectoryService(serviceAccountFilePath string, email string) (*admin.Service, error) { + jsonCredentials, err := ioutil.ReadFile(serviceAccountFilePath) + if err != nil { + return nil, fmt.Errorf("error reading credentials from file: %v", err) + } + + config, err := google.JWTConfigFromJSON(jsonCredentials, admin.AdminDirectoryGroupReadonlyScope) + if err != nil { + return nil, fmt.Errorf("unable to parse client secret file to config: %v", err) + } + + config.Subject = email + + ctx := context.Background() + client := config.Client(ctx) + + srv, err := admin.New(client) + if err != nil { + return nil, fmt.Errorf("unable to create directory service %v", err) + } + return srv, nil +} From c03c98b95187f1f9a8dec6102340b1af517f96fb Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Mon, 5 Feb 2018 21:33:17 +0000 Subject: [PATCH 45/72] Check config before getting groups --- connector/google/google.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/connector/google/google.go b/connector/google/google.go index 0bfe1290..6e6a70d2 100644 --- a/connector/google/google.go +++ b/connector/google/google.go @@ -200,7 +200,7 @@ func (c *googleConnector) createIdentity(ctx context.Context, identity connector } var groups []string - if s.Groups { + if s.Groups && c.adminEmail != "" && c.serviceAccountFilePath != "" { groups, err = c.getGroups(claims.Email) if err != nil { return identity, fmt.Errorf("google: could not retrieve groups: %v", err) From 6a9bc889b55c9bb51c680970624ab86ca32df622 Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Mon, 5 Feb 2018 21:53:32 +0000 Subject: [PATCH 46/72] Update comments --- connector/google/google.go | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/connector/google/google.go b/connector/google/google.go index 6e6a70d2..ec2a6189 100644 --- a/connector/google/google.go +++ b/connector/google/google.go @@ -22,7 +22,7 @@ const ( issuerURL = "https://accounts.google.com" ) -// Config holds configuration options for OpenID Connect logins. +// Config holds configuration options for Google logins. type Config struct { ClientID string `json:"clientID"` ClientSecret string `json:"clientSecret"` @@ -45,8 +45,7 @@ type Config struct { AdminEmail string } -// Open returns a connector which can be used to login users through an upstream -// OpenID Connect provider. +// Open returns a connector which can be used to login users through Google. func (c *Config) Open(id string, logger log.Logger) (conn connector.Connector, err error) { ctx, cancel := context.WithCancel(context.Background()) @@ -151,7 +150,6 @@ func (c *googleConnector) HandleCallback(s connector.Scopes, r *http.Request) (i return c.createIdentity(r.Context(), identity, s, token) } -// Refresh is implemented for backwards compatibility, even though it's a no-op. func (c *googleConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) { t := &oauth2.Token{ RefreshToken: string(identity.ConnectorData), @@ -218,6 +216,8 @@ func (c *googleConnector) createIdentity(ctx context.Context, identity connector return identity, nil } +// getGroups creates a connection to the admin directory service and lists +// all groups the user is a member of func (c *googleConnector) getGroups(email string) ([]string, error) { srv, err := createDirectoryService(c.serviceAccountFilePath, c.adminEmail) if err != nil { @@ -237,6 +237,9 @@ func (c *googleConnector) getGroups(email string) ([]string, error) { return userGroups, nil } +// createDirectoryService loads a google service account credentials file, +// sets up super user impersonation and creates an admin client for calling +// the google admin api func createDirectoryService(serviceAccountFilePath string, email string) (*admin.Service, error) { jsonCredentials, err := ioutil.ReadFile(serviceAccountFilePath) if err != nil { @@ -248,6 +251,7 @@ func createDirectoryService(serviceAccountFilePath string, email string) (*admin return nil, fmt.Errorf("unable to parse client secret file to config: %v", err) } + // Impersonate an admin. This is mandatory for the admin APIs. config.Subject = email ctx := context.Background() From 9d9a1017e46f137c4db80ce433bd31546e5a5b1e Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Mon, 5 Feb 2018 22:15:29 +0000 Subject: [PATCH 47/72] Add documentation for google connector --- Documentation/connectors/google.md | 53 ++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Documentation/connectors/google.md diff --git a/Documentation/connectors/google.md b/Documentation/connectors/google.md new file mode 100644 index 00000000..1bfe321c --- /dev/null +++ b/Documentation/connectors/google.md @@ -0,0 +1,53 @@ +# Authentication through Google + +## Overview + +Dex is able to use Google's OpenID Connect provider as an authentication source. + +The connector uses the same authentication flow as the OpenID Connect provider but adds Google specific features such as Hosted domain support and reading groups using a service account. + +## Configuration + +```yaml +connectors: +- type: google + id: google + name: Google + config: + + # Connector config values starting with a "$" will read from the environment. + clientID: $GOOGLE_CLIENT_ID + clientSecret: $GOOGLE_CLIENT_SECRET + + # Dex's issuer URL + "/callback" + redirectURI: http://127.0.0.1:5556/callback + + # Google supports whitelisting allowed domains when using G Suite + # (Google Apps). The following field can be set to a list of domains + # that can log in: + # + # hostedDomains: + # - example.com + + # Google does not support the OpenID Connect groups claim and only supports + # fetching a user's group membership with a service account. + # This service account requires an authentication JSON file and the email + # of a G Suite admin to impersonate: + # + #serviceAccountFilePath: googleAuth.json + #adminEmail: super-user@example.com +``` + +## Fetching groups from Google +To allow Dex to fetch group information from Google, you will need to configure a service account for Dex to use. +This account needs Domain-Wide Delegation and permission to access the `https://www.googleapis.com/auth/admin.directory.group.readonly` API scope. + +To get group fetching set up: + +1. Follow the [instructions](https://developers.google.com/admin-sdk/directory/v1/guides/delegation) to set up a service account with Domain-Wide Delegation + - During service account creation, a JSON key file will be created that contains authentication information for the service account. This needs storing in a location accessible by Dex and you will set the `serviceAccountFilePath` to point at it. + - When delegating the API scopes to the service account, delegate the `https://www.googleapis.com/auth/admin.directory.group.readonly` scope and only this scope. If you delegate more scopes to the service account, it will not be able to access the API. +2. Enable the [Admin SDK](https://console.developers.google.com/apis/library/admin.googleapis.com/) +3. Add the `serviceAccountFilePath` and `adminEmail` configuration options to your Dex config. + - `serviceAccountFilePath` should point to the location of the service account JSON key file + - `adminEmail` should be the email of a G Suite super user. The service account you created earlier will impersonate this user when making calls to the admin API. A valid user should be able to retrieve a list of groups when [testing the API](https://developers.google.com/admin-sdk/directory/v1/reference/groups/list#try-it). From 94bee18f6be02df25e84fbc1f7dfe68fc84868cf Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Tue, 6 Feb 2018 22:27:49 +0000 Subject: [PATCH 48/72] vendor: make revendor --- go.mod | 1 + go.sum | 38 +- vendor/cloud.google.com/go/LICENSE | 202 + .../go/compute/metadata/metadata.go | 513 + .../github.com/googleapis/gax-go/v2/LICENSE | 27 + .../googleapis/gax-go/v2/call_option.go | 161 + vendor/github.com/googleapis/gax-go/v2/gax.go | 39 + vendor/github.com/googleapis/gax-go/v2/go.mod | 3 + vendor/github.com/googleapis/gax-go/v2/go.sum | 25 + .../github.com/googleapis/gax-go/v2/header.go | 53 + .../github.com/googleapis/gax-go/v2/invoke.go | 99 + .../github.com/hashicorp/golang-lru/LICENSE | 362 + .../hashicorp/golang-lru/simplelru/lru.go | 161 + .../golang-lru/simplelru/lru_interface.go | 36 + vendor/go.opencensus.io/.gitignore | 9 + vendor/go.opencensus.io/.travis.yml | 17 + vendor/go.opencensus.io/AUTHORS | 1 + vendor/go.opencensus.io/CONTRIBUTING.md | 63 + vendor/go.opencensus.io/Gopkg.lock | 231 + vendor/go.opencensus.io/Gopkg.toml | 36 + vendor/go.opencensus.io/LICENSE | 202 + vendor/go.opencensus.io/Makefile | 96 + vendor/go.opencensus.io/README.md | 263 + vendor/go.opencensus.io/appveyor.yml | 25 + vendor/go.opencensus.io/go.mod | 10 + vendor/go.opencensus.io/go.sum | 50 + vendor/go.opencensus.io/internal/internal.go | 37 + vendor/go.opencensus.io/internal/sanitize.go | 50 + .../internal/tagencoding/tagencoding.go | 75 + .../internal/traceinternals.go | 53 + .../go.opencensus.io/metric/metricdata/doc.go | 19 + .../metric/metricdata/exemplar.go | 38 + .../metric/metricdata/label.go | 35 + .../metric/metricdata/metric.go | 46 + .../metric/metricdata/point.go | 193 + .../metric/metricdata/type_string.go | 16 + .../metric/metricdata/unit.go | 27 + .../metric/metricproducer/manager.go | 78 + .../metric/metricproducer/producer.go | 28 + vendor/go.opencensus.io/opencensus.go | 21 + .../go.opencensus.io/plugin/ochttp/client.go | 117 + .../plugin/ochttp/client_stats.go | 143 + vendor/go.opencensus.io/plugin/ochttp/doc.go | 19 + .../plugin/ochttp/propagation/b3/b3.go | 123 + .../go.opencensus.io/plugin/ochttp/route.go | 61 + .../go.opencensus.io/plugin/ochttp/server.go | 449 + .../ochttp/span_annotating_client_trace.go | 169 + .../go.opencensus.io/plugin/ochttp/stats.go | 292 + .../go.opencensus.io/plugin/ochttp/trace.go | 239 + .../plugin/ochttp/wrapped_body.go | 44 + vendor/go.opencensus.io/resource/resource.go | 164 + vendor/go.opencensus.io/stats/doc.go | 69 + .../go.opencensus.io/stats/internal/record.go | 25 + vendor/go.opencensus.io/stats/measure.go | 109 + .../go.opencensus.io/stats/measure_float64.go | 55 + .../go.opencensus.io/stats/measure_int64.go | 55 + vendor/go.opencensus.io/stats/record.go | 117 + vendor/go.opencensus.io/stats/units.go | 25 + .../stats/view/aggregation.go | 120 + .../stats/view/aggregation_data.go | 293 + .../go.opencensus.io/stats/view/collector.go | 86 + vendor/go.opencensus.io/stats/view/doc.go | 47 + vendor/go.opencensus.io/stats/view/export.go | 58 + vendor/go.opencensus.io/stats/view/view.go | 221 + .../stats/view/view_to_metric.go | 140 + vendor/go.opencensus.io/stats/view/worker.go | 281 + .../stats/view/worker_commands.go | 186 + vendor/go.opencensus.io/tag/context.go | 43 + vendor/go.opencensus.io/tag/doc.go | 26 + vendor/go.opencensus.io/tag/key.go | 35 + vendor/go.opencensus.io/tag/map.go | 229 + vendor/go.opencensus.io/tag/map_codec.go | 239 + vendor/go.opencensus.io/tag/metadata.go | 52 + vendor/go.opencensus.io/tag/profile_19.go | 31 + vendor/go.opencensus.io/tag/profile_not19.go | 23 + vendor/go.opencensus.io/tag/validate.go | 56 + vendor/go.opencensus.io/trace/basetypes.go | 119 + vendor/go.opencensus.io/trace/config.go | 86 + vendor/go.opencensus.io/trace/doc.go | 53 + vendor/go.opencensus.io/trace/evictedqueue.go | 38 + vendor/go.opencensus.io/trace/export.go | 97 + .../trace/internal/internal.go | 22 + vendor/go.opencensus.io/trace/lrumap.go | 37 + .../trace/propagation/propagation.go | 108 + vendor/go.opencensus.io/trace/sampling.go | 75 + vendor/go.opencensus.io/trace/spanbucket.go | 130 + vendor/go.opencensus.io/trace/spanstore.go | 306 + vendor/go.opencensus.io/trace/status_codes.go | 37 + vendor/go.opencensus.io/trace/trace.go | 598 + vendor/go.opencensus.io/trace/trace_go11.go | 32 + .../go.opencensus.io/trace/trace_nongo11.go | 25 + .../trace/tracestate/tracestate.go | 147 + .../golang.org/x/oauth2/google/appengine.go | 38 + .../x/oauth2/google/appengine_gen1.go | 77 + .../x/oauth2/google/appengine_gen2_flex.go | 27 + vendor/golang.org/x/oauth2/google/default.go | 154 + vendor/golang.org/x/oauth2/google/doc.go | 40 + vendor/golang.org/x/oauth2/google/google.go | 209 + vendor/golang.org/x/oauth2/google/jwt.go | 74 + vendor/golang.org/x/oauth2/google/sdk.go | 201 + vendor/golang.org/x/oauth2/jws/jws.go | 182 + vendor/golang.org/x/oauth2/jwt/jwt.go | 185 + vendor/google.golang.org/api/AUTHORS | 10 + vendor/google.golang.org/api/CONTRIBUTORS | 55 + vendor/google.golang.org/api/LICENSE | 27 + .../api/admin/directory/v1/admin-api.json | 7034 +++++ .../api/admin/directory/v1/admin-gen.go | 21696 ++++++++++++++++ .../api/gensupport/buffer.go | 79 + .../google.golang.org/api/gensupport/doc.go | 10 + .../google.golang.org/api/gensupport/json.go | 211 + .../api/gensupport/jsonfloat.go | 57 + .../google.golang.org/api/gensupport/media.go | 363 + .../api/gensupport/params.go | 51 + .../api/gensupport/resumable.go | 241 + .../google.golang.org/api/gensupport/send.go | 87 + .../api/googleapi/googleapi.go | 403 + .../googleapi/internal/uritemplates/LICENSE | 18 + .../internal/uritemplates/uritemplates.go | 248 + .../googleapi/internal/uritemplates/utils.go | 17 + .../api/googleapi/transport/apikey.go | 38 + .../google.golang.org/api/googleapi/types.go | 202 + .../google.golang.org/api/internal/creds.go | 102 + vendor/google.golang.org/api/internal/pool.go | 61 + .../api/internal/service-account.json | 12 + .../api/internal/settings.go | 96 + .../api/option/credentials_go19.go | 33 + .../api/option/credentials_notgo19.go | 32 + vendor/google.golang.org/api/option/option.go | 235 + .../api/transport/http/dial.go | 161 + .../api/transport/http/dial_appengine.go | 30 + .../http/internal/propagation/http.go | 96 + .../google.golang.org/appengine/.travis.yml | 20 + .../appengine/CONTRIBUTING.md | 90 + vendor/google.golang.org/appengine/README.md | 100 + .../google.golang.org/appengine/appengine.go | 135 + .../appengine/appengine_vm.go | 20 + vendor/google.golang.org/appengine/errors.go | 46 + vendor/google.golang.org/appengine/go.mod | 10 + vendor/google.golang.org/appengine/go.sum | 22 + .../google.golang.org/appengine/identity.go | 142 + .../app_identity/app_identity_service.pb.go | 611 + .../app_identity/app_identity_service.proto | 64 + .../internal/modules/modules_service.pb.go | 786 + .../internal/modules/modules_service.proto | 80 + .../google.golang.org/appengine/namespace.go | 25 + vendor/google.golang.org/appengine/timeout.go | 20 + .../appengine/travis_install.sh | 18 + .../appengine/travis_test.sh | 12 + vendor/modules.txt | 41 +- 149 files changed, 44922 insertions(+), 2 deletions(-) create mode 100644 vendor/cloud.google.com/go/LICENSE create mode 100644 vendor/cloud.google.com/go/compute/metadata/metadata.go create mode 100644 vendor/github.com/googleapis/gax-go/v2/LICENSE create mode 100644 vendor/github.com/googleapis/gax-go/v2/call_option.go create mode 100644 vendor/github.com/googleapis/gax-go/v2/gax.go create mode 100644 vendor/github.com/googleapis/gax-go/v2/go.mod create mode 100644 vendor/github.com/googleapis/gax-go/v2/go.sum create mode 100644 vendor/github.com/googleapis/gax-go/v2/header.go create mode 100644 vendor/github.com/googleapis/gax-go/v2/invoke.go create mode 100644 vendor/github.com/hashicorp/golang-lru/LICENSE create mode 100644 vendor/github.com/hashicorp/golang-lru/simplelru/lru.go create mode 100644 vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go create mode 100644 vendor/go.opencensus.io/.gitignore create mode 100644 vendor/go.opencensus.io/.travis.yml create mode 100644 vendor/go.opencensus.io/AUTHORS create mode 100644 vendor/go.opencensus.io/CONTRIBUTING.md create mode 100644 vendor/go.opencensus.io/Gopkg.lock create mode 100644 vendor/go.opencensus.io/Gopkg.toml create mode 100644 vendor/go.opencensus.io/LICENSE create mode 100644 vendor/go.opencensus.io/Makefile create mode 100644 vendor/go.opencensus.io/README.md create mode 100644 vendor/go.opencensus.io/appveyor.yml create mode 100644 vendor/go.opencensus.io/go.mod create mode 100644 vendor/go.opencensus.io/go.sum create mode 100644 vendor/go.opencensus.io/internal/internal.go create mode 100644 vendor/go.opencensus.io/internal/sanitize.go create mode 100644 vendor/go.opencensus.io/internal/tagencoding/tagencoding.go create mode 100644 vendor/go.opencensus.io/internal/traceinternals.go create mode 100644 vendor/go.opencensus.io/metric/metricdata/doc.go create mode 100644 vendor/go.opencensus.io/metric/metricdata/exemplar.go create mode 100644 vendor/go.opencensus.io/metric/metricdata/label.go create mode 100644 vendor/go.opencensus.io/metric/metricdata/metric.go create mode 100644 vendor/go.opencensus.io/metric/metricdata/point.go create mode 100644 vendor/go.opencensus.io/metric/metricdata/type_string.go create mode 100644 vendor/go.opencensus.io/metric/metricdata/unit.go create mode 100644 vendor/go.opencensus.io/metric/metricproducer/manager.go create mode 100644 vendor/go.opencensus.io/metric/metricproducer/producer.go create mode 100644 vendor/go.opencensus.io/opencensus.go create mode 100644 vendor/go.opencensus.io/plugin/ochttp/client.go create mode 100644 vendor/go.opencensus.io/plugin/ochttp/client_stats.go create mode 100644 vendor/go.opencensus.io/plugin/ochttp/doc.go create mode 100644 vendor/go.opencensus.io/plugin/ochttp/propagation/b3/b3.go create mode 100644 vendor/go.opencensus.io/plugin/ochttp/route.go create mode 100644 vendor/go.opencensus.io/plugin/ochttp/server.go create mode 100644 vendor/go.opencensus.io/plugin/ochttp/span_annotating_client_trace.go create mode 100644 vendor/go.opencensus.io/plugin/ochttp/stats.go create mode 100644 vendor/go.opencensus.io/plugin/ochttp/trace.go create mode 100644 vendor/go.opencensus.io/plugin/ochttp/wrapped_body.go create mode 100644 vendor/go.opencensus.io/resource/resource.go create mode 100644 vendor/go.opencensus.io/stats/doc.go create mode 100644 vendor/go.opencensus.io/stats/internal/record.go create mode 100644 vendor/go.opencensus.io/stats/measure.go create mode 100644 vendor/go.opencensus.io/stats/measure_float64.go create mode 100644 vendor/go.opencensus.io/stats/measure_int64.go create mode 100644 vendor/go.opencensus.io/stats/record.go create mode 100644 vendor/go.opencensus.io/stats/units.go create mode 100644 vendor/go.opencensus.io/stats/view/aggregation.go create mode 100644 vendor/go.opencensus.io/stats/view/aggregation_data.go create mode 100644 vendor/go.opencensus.io/stats/view/collector.go create mode 100644 vendor/go.opencensus.io/stats/view/doc.go create mode 100644 vendor/go.opencensus.io/stats/view/export.go create mode 100644 vendor/go.opencensus.io/stats/view/view.go create mode 100644 vendor/go.opencensus.io/stats/view/view_to_metric.go create mode 100644 vendor/go.opencensus.io/stats/view/worker.go create mode 100644 vendor/go.opencensus.io/stats/view/worker_commands.go create mode 100644 vendor/go.opencensus.io/tag/context.go create mode 100644 vendor/go.opencensus.io/tag/doc.go create mode 100644 vendor/go.opencensus.io/tag/key.go create mode 100644 vendor/go.opencensus.io/tag/map.go create mode 100644 vendor/go.opencensus.io/tag/map_codec.go create mode 100644 vendor/go.opencensus.io/tag/metadata.go create mode 100644 vendor/go.opencensus.io/tag/profile_19.go create mode 100644 vendor/go.opencensus.io/tag/profile_not19.go create mode 100644 vendor/go.opencensus.io/tag/validate.go create mode 100644 vendor/go.opencensus.io/trace/basetypes.go create mode 100644 vendor/go.opencensus.io/trace/config.go create mode 100644 vendor/go.opencensus.io/trace/doc.go create mode 100644 vendor/go.opencensus.io/trace/evictedqueue.go create mode 100644 vendor/go.opencensus.io/trace/export.go create mode 100644 vendor/go.opencensus.io/trace/internal/internal.go create mode 100644 vendor/go.opencensus.io/trace/lrumap.go create mode 100644 vendor/go.opencensus.io/trace/propagation/propagation.go create mode 100644 vendor/go.opencensus.io/trace/sampling.go create mode 100644 vendor/go.opencensus.io/trace/spanbucket.go create mode 100644 vendor/go.opencensus.io/trace/spanstore.go create mode 100644 vendor/go.opencensus.io/trace/status_codes.go create mode 100644 vendor/go.opencensus.io/trace/trace.go create mode 100644 vendor/go.opencensus.io/trace/trace_go11.go create mode 100644 vendor/go.opencensus.io/trace/trace_nongo11.go create mode 100644 vendor/go.opencensus.io/trace/tracestate/tracestate.go create mode 100644 vendor/golang.org/x/oauth2/google/appengine.go create mode 100644 vendor/golang.org/x/oauth2/google/appengine_gen1.go create mode 100644 vendor/golang.org/x/oauth2/google/appengine_gen2_flex.go create mode 100644 vendor/golang.org/x/oauth2/google/default.go create mode 100644 vendor/golang.org/x/oauth2/google/doc.go create mode 100644 vendor/golang.org/x/oauth2/google/google.go create mode 100644 vendor/golang.org/x/oauth2/google/jwt.go create mode 100644 vendor/golang.org/x/oauth2/google/sdk.go create mode 100644 vendor/golang.org/x/oauth2/jws/jws.go create mode 100644 vendor/golang.org/x/oauth2/jwt/jwt.go create mode 100644 vendor/google.golang.org/api/AUTHORS create mode 100644 vendor/google.golang.org/api/CONTRIBUTORS create mode 100644 vendor/google.golang.org/api/LICENSE create mode 100644 vendor/google.golang.org/api/admin/directory/v1/admin-api.json create mode 100644 vendor/google.golang.org/api/admin/directory/v1/admin-gen.go create mode 100644 vendor/google.golang.org/api/gensupport/buffer.go create mode 100644 vendor/google.golang.org/api/gensupport/doc.go create mode 100644 vendor/google.golang.org/api/gensupport/json.go create mode 100644 vendor/google.golang.org/api/gensupport/jsonfloat.go create mode 100644 vendor/google.golang.org/api/gensupport/media.go create mode 100644 vendor/google.golang.org/api/gensupport/params.go create mode 100644 vendor/google.golang.org/api/gensupport/resumable.go create mode 100644 vendor/google.golang.org/api/gensupport/send.go create mode 100644 vendor/google.golang.org/api/googleapi/googleapi.go create mode 100644 vendor/google.golang.org/api/googleapi/internal/uritemplates/LICENSE create mode 100644 vendor/google.golang.org/api/googleapi/internal/uritemplates/uritemplates.go create mode 100644 vendor/google.golang.org/api/googleapi/internal/uritemplates/utils.go create mode 100644 vendor/google.golang.org/api/googleapi/transport/apikey.go create mode 100644 vendor/google.golang.org/api/googleapi/types.go create mode 100644 vendor/google.golang.org/api/internal/creds.go create mode 100644 vendor/google.golang.org/api/internal/pool.go create mode 100644 vendor/google.golang.org/api/internal/service-account.json create mode 100644 vendor/google.golang.org/api/internal/settings.go create mode 100644 vendor/google.golang.org/api/option/credentials_go19.go create mode 100644 vendor/google.golang.org/api/option/credentials_notgo19.go create mode 100644 vendor/google.golang.org/api/option/option.go create mode 100644 vendor/google.golang.org/api/transport/http/dial.go create mode 100644 vendor/google.golang.org/api/transport/http/dial_appengine.go create mode 100644 vendor/google.golang.org/api/transport/http/internal/propagation/http.go create mode 100644 vendor/google.golang.org/appengine/.travis.yml create mode 100644 vendor/google.golang.org/appengine/CONTRIBUTING.md create mode 100644 vendor/google.golang.org/appengine/README.md create mode 100644 vendor/google.golang.org/appengine/appengine.go create mode 100644 vendor/google.golang.org/appengine/appengine_vm.go create mode 100644 vendor/google.golang.org/appengine/errors.go create mode 100644 vendor/google.golang.org/appengine/go.mod create mode 100644 vendor/google.golang.org/appengine/go.sum create mode 100644 vendor/google.golang.org/appengine/identity.go create mode 100644 vendor/google.golang.org/appengine/internal/app_identity/app_identity_service.pb.go create mode 100644 vendor/google.golang.org/appengine/internal/app_identity/app_identity_service.proto create mode 100644 vendor/google.golang.org/appengine/internal/modules/modules_service.pb.go create mode 100644 vendor/google.golang.org/appengine/internal/modules/modules_service.proto create mode 100644 vendor/google.golang.org/appengine/namespace.go create mode 100644 vendor/google.golang.org/appengine/timeout.go create mode 100644 vendor/google.golang.org/appengine/travis_install.sh create mode 100644 vendor/google.golang.org/appengine/travis_test.sh diff --git a/go.mod b/go.mod index 4d311f5f..78315f1b 100644 --- a/go.mod +++ b/go.mod @@ -52,6 +52,7 @@ require ( golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a // indirect golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 // indirect golang.org/x/tools v0.0.0-20190813214729-9dba7caff850 // indirect + google.golang.org/api v0.10.0 google.golang.org/appengine v1.6.1 // indirect google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64 // indirect google.golang.org/grpc v1.23.0 diff --git a/go.sum b/go.sum index 08351488..9cf627f7 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0 h1:eOI3/cP2VTU6uZLDYAoic+eyzzB9YyGmJ7eIjl8rOPg= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0 h1:ROfEUZz+Gh5pa62DJWXSaonyu3StP6EA6lPEXPI6mCo= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= @@ -52,22 +55,30 @@ github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfU github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 h1:ZgQEtGgCBiWRM39fZuwSd1LwSqqSW0hOdXCYYDX0R3I= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gorilla/handlers v1.4.2 h1:0QniY0USkHQ1RGCLfKxeNHK9bkDHGRYGNDFBCS+YARg= github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ= github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/grpc-ecosystem/go-grpc-middleware v1.0.0 h1:Iju5GlWwrvL6UBg4zJJt3btmonfrMlCDdsejg4CZE7c= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.0 h1:BWIsLfhgKhV5g/oF34aRjniBHLTZe5DNekSjbAjIS6c= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= @@ -75,6 +86,9 @@ github.com/grpc-ecosystem/grpc-gateway v1.9.5 h1:UImYN5qQ8tuGpGE16ZmjvcTtTw24zw1 github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/gtank/cryptopasta v0.0.0-20170601214702-1f550f6f2f69 h1:7xsUJsB2NrdcttQPa7JLEaGzvdbk7KvfrjgHZXOQRo0= github.com/gtank/cryptopasta v0.0.0-20170601214702-1f550f6f2f69/go.mod h1:YLEMZOtU+AZ7dhN9T/IpGhXVGly2bvkJQ+zxj3WeVQo= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= @@ -83,6 +97,7 @@ github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22 github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7 h1:KfgG9LzI+pYjr4xvmz/5H4FXjokeP+rlHLhv3iH62Fo= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= @@ -165,6 +180,8 @@ github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= go.etcd.io/bbolt v1.3.3 h1:MUGmc65QhB3pIlaQ5bB4LwqSj6GIonVJXpZiaKNyaKk= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.opencensus.io v0.21.0 h1:mU6zScU4U1YAFPHEHYk+3JC4SY7JxgkqS10ZOSyksNg= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= @@ -181,6 +198,7 @@ golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3 h1:x/bBzNauLQAlE3fLku/xy92Y8QwKX5HZymrMz2IiKFc= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190409202823-959b441ac422 h1:QzoH/1pFpZguR8NrRHLcO6jKqfv2zpuSqZLgdm7ZmjI= golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= @@ -192,18 +210,21 @@ golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7 h1:fHDIZ2oxGnUZRN6WgWFCbYBjH9uqVPRCUVUDhs0wnbA= golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f h1:Bl/8QSvNqXvPGPGXa2z5xUTmV7VDcZyvRZ+QQXkXTZQ= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -213,12 +234,15 @@ golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 h1:SvFZT6jyqRaOeXpc5h/JSfZenJ2O330aBsf7JfSUXmQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -226,19 +250,29 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190813214729-9dba7caff850 h1:I+2i9HEjvv+3iJrNMhjMJOMF/FXz9eI08iBlDF4w24I= golang.org/x/tools v0.0.0-20190813214729-9dba7caff850/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.10.0 h1:7tmAxx3oKE98VMZ+SBZzvYYWRQ9HODBxmC8mXUsraSQ= +google.golang.org/api v0.10.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.1 h1:QzqyMA1tlu6CgqCDUtU9V+ZKhLFT2dkJuANu5QaxI3I= google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64 h1:iKtrH9Y8mcbADOP0YFaEMth7OfuHY9xHOwNj4znpM1A= google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.23.0 h1:AzbTB6ux+okLTzP8Ru1Xs41C303zdcfEht7MQnYJt5A= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= @@ -257,4 +291,6 @@ gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/vendor/cloud.google.com/go/LICENSE b/vendor/cloud.google.com/go/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/cloud.google.com/go/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/cloud.google.com/go/compute/metadata/metadata.go b/vendor/cloud.google.com/go/compute/metadata/metadata.go new file mode 100644 index 00000000..125b7033 --- /dev/null +++ b/vendor/cloud.google.com/go/compute/metadata/metadata.go @@ -0,0 +1,513 @@ +// Copyright 2014 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package metadata provides access to Google Compute Engine (GCE) +// metadata and API service accounts. +// +// This package is a wrapper around the GCE metadata service, +// as documented at https://developers.google.com/compute/docs/metadata. +package metadata // import "cloud.google.com/go/compute/metadata" + +import ( + "context" + "encoding/json" + "fmt" + "io/ioutil" + "net" + "net/http" + "net/url" + "os" + "runtime" + "strings" + "sync" + "time" +) + +const ( + // metadataIP is the documented metadata server IP address. + metadataIP = "169.254.169.254" + + // metadataHostEnv is the environment variable specifying the + // GCE metadata hostname. If empty, the default value of + // metadataIP ("169.254.169.254") is used instead. + // This is variable name is not defined by any spec, as far as + // I know; it was made up for the Go package. + metadataHostEnv = "GCE_METADATA_HOST" + + userAgent = "gcloud-golang/0.1" +) + +type cachedValue struct { + k string + trim bool + mu sync.Mutex + v string +} + +var ( + projID = &cachedValue{k: "project/project-id", trim: true} + projNum = &cachedValue{k: "project/numeric-project-id", trim: true} + instID = &cachedValue{k: "instance/id", trim: true} +) + +var ( + defaultClient = &Client{hc: &http.Client{ + Transport: &http.Transport{ + Dial: (&net.Dialer{ + Timeout: 2 * time.Second, + KeepAlive: 30 * time.Second, + }).Dial, + ResponseHeaderTimeout: 2 * time.Second, + }, + }} + subscribeClient = &Client{hc: &http.Client{ + Transport: &http.Transport{ + Dial: (&net.Dialer{ + Timeout: 2 * time.Second, + KeepAlive: 30 * time.Second, + }).Dial, + }, + }} +) + +// NotDefinedError is returned when requested metadata is not defined. +// +// The underlying string is the suffix after "/computeMetadata/v1/". +// +// This error is not returned if the value is defined to be the empty +// string. +type NotDefinedError string + +func (suffix NotDefinedError) Error() string { + return fmt.Sprintf("metadata: GCE metadata %q not defined", string(suffix)) +} + +func (c *cachedValue) get(cl *Client) (v string, err error) { + defer c.mu.Unlock() + c.mu.Lock() + if c.v != "" { + return c.v, nil + } + if c.trim { + v, err = cl.getTrimmed(c.k) + } else { + v, err = cl.Get(c.k) + } + if err == nil { + c.v = v + } + return +} + +var ( + onGCEOnce sync.Once + onGCE bool +) + +// OnGCE reports whether this process is running on Google Compute Engine. +func OnGCE() bool { + onGCEOnce.Do(initOnGCE) + return onGCE +} + +func initOnGCE() { + onGCE = testOnGCE() +} + +func testOnGCE() bool { + // The user explicitly said they're on GCE, so trust them. + if os.Getenv(metadataHostEnv) != "" { + return true + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + resc := make(chan bool, 2) + + // Try two strategies in parallel. + // See https://github.com/googleapis/google-cloud-go/issues/194 + go func() { + req, _ := http.NewRequest("GET", "http://"+metadataIP, nil) + req.Header.Set("User-Agent", userAgent) + res, err := defaultClient.hc.Do(req.WithContext(ctx)) + if err != nil { + resc <- false + return + } + defer res.Body.Close() + resc <- res.Header.Get("Metadata-Flavor") == "Google" + }() + + go func() { + addrs, err := net.LookupHost("metadata.google.internal") + if err != nil || len(addrs) == 0 { + resc <- false + return + } + resc <- strsContains(addrs, metadataIP) + }() + + tryHarder := systemInfoSuggestsGCE() + if tryHarder { + res := <-resc + if res { + // The first strategy succeeded, so let's use it. + return true + } + // Wait for either the DNS or metadata server probe to + // contradict the other one and say we are running on + // GCE. Give it a lot of time to do so, since the system + // info already suggests we're running on a GCE BIOS. + timer := time.NewTimer(5 * time.Second) + defer timer.Stop() + select { + case res = <-resc: + return res + case <-timer.C: + // Too slow. Who knows what this system is. + return false + } + } + + // There's no hint from the system info that we're running on + // GCE, so use the first probe's result as truth, whether it's + // true or false. The goal here is to optimize for speed for + // users who are NOT running on GCE. We can't assume that + // either a DNS lookup or an HTTP request to a blackholed IP + // address is fast. Worst case this should return when the + // metaClient's Transport.ResponseHeaderTimeout or + // Transport.Dial.Timeout fires (in two seconds). + return <-resc +} + +// systemInfoSuggestsGCE reports whether the local system (without +// doing network requests) suggests that we're running on GCE. If this +// returns true, testOnGCE tries a bit harder to reach its metadata +// server. +func systemInfoSuggestsGCE() bool { + if runtime.GOOS != "linux" { + // We don't have any non-Linux clues available, at least yet. + return false + } + slurp, _ := ioutil.ReadFile("/sys/class/dmi/id/product_name") + name := strings.TrimSpace(string(slurp)) + return name == "Google" || name == "Google Compute Engine" +} + +// Subscribe calls Client.Subscribe on a client designed for subscribing (one with no +// ResponseHeaderTimeout). +func Subscribe(suffix string, fn func(v string, ok bool) error) error { + return subscribeClient.Subscribe(suffix, fn) +} + +// Get calls Client.Get on the default client. +func Get(suffix string) (string, error) { return defaultClient.Get(suffix) } + +// ProjectID returns the current instance's project ID string. +func ProjectID() (string, error) { return defaultClient.ProjectID() } + +// NumericProjectID returns the current instance's numeric project ID. +func NumericProjectID() (string, error) { return defaultClient.NumericProjectID() } + +// InternalIP returns the instance's primary internal IP address. +func InternalIP() (string, error) { return defaultClient.InternalIP() } + +// ExternalIP returns the instance's primary external (public) IP address. +func ExternalIP() (string, error) { return defaultClient.ExternalIP() } + +// Hostname returns the instance's hostname. This will be of the form +// ".c..internal". +func Hostname() (string, error) { return defaultClient.Hostname() } + +// InstanceTags returns the list of user-defined instance tags, +// assigned when initially creating a GCE instance. +func InstanceTags() ([]string, error) { return defaultClient.InstanceTags() } + +// InstanceID returns the current VM's numeric instance ID. +func InstanceID() (string, error) { return defaultClient.InstanceID() } + +// InstanceName returns the current VM's instance ID string. +func InstanceName() (string, error) { return defaultClient.InstanceName() } + +// Zone returns the current VM's zone, such as "us-central1-b". +func Zone() (string, error) { return defaultClient.Zone() } + +// InstanceAttributes calls Client.InstanceAttributes on the default client. +func InstanceAttributes() ([]string, error) { return defaultClient.InstanceAttributes() } + +// ProjectAttributes calls Client.ProjectAttributes on the default client. +func ProjectAttributes() ([]string, error) { return defaultClient.ProjectAttributes() } + +// InstanceAttributeValue calls Client.InstanceAttributeValue on the default client. +func InstanceAttributeValue(attr string) (string, error) { + return defaultClient.InstanceAttributeValue(attr) +} + +// ProjectAttributeValue calls Client.ProjectAttributeValue on the default client. +func ProjectAttributeValue(attr string) (string, error) { + return defaultClient.ProjectAttributeValue(attr) +} + +// Scopes calls Client.Scopes on the default client. +func Scopes(serviceAccount string) ([]string, error) { return defaultClient.Scopes(serviceAccount) } + +func strsContains(ss []string, s string) bool { + for _, v := range ss { + if v == s { + return true + } + } + return false +} + +// A Client provides metadata. +type Client struct { + hc *http.Client +} + +// NewClient returns a Client that can be used to fetch metadata. All HTTP requests +// will use the given http.Client instead of the default client. +func NewClient(c *http.Client) *Client { + return &Client{hc: c} +} + +// getETag returns a value from the metadata service as well as the associated ETag. +// This func is otherwise equivalent to Get. +func (c *Client) getETag(suffix string) (value, etag string, err error) { + // Using a fixed IP makes it very difficult to spoof the metadata service in + // a container, which is an important use-case for local testing of cloud + // deployments. To enable spoofing of the metadata service, the environment + // variable GCE_METADATA_HOST is first inspected to decide where metadata + // requests shall go. + host := os.Getenv(metadataHostEnv) + if host == "" { + // Using 169.254.169.254 instead of "metadata" here because Go + // binaries built with the "netgo" tag and without cgo won't + // know the search suffix for "metadata" is + // ".google.internal", and this IP address is documented as + // being stable anyway. + host = metadataIP + } + u := "http://" + host + "/computeMetadata/v1/" + suffix + req, _ := http.NewRequest("GET", u, nil) + req.Header.Set("Metadata-Flavor", "Google") + req.Header.Set("User-Agent", userAgent) + res, err := c.hc.Do(req) + if err != nil { + return "", "", err + } + defer res.Body.Close() + if res.StatusCode == http.StatusNotFound { + return "", "", NotDefinedError(suffix) + } + all, err := ioutil.ReadAll(res.Body) + if err != nil { + return "", "", err + } + if res.StatusCode != 200 { + return "", "", &Error{Code: res.StatusCode, Message: string(all)} + } + return string(all), res.Header.Get("Etag"), nil +} + +// Get returns a value from the metadata service. +// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/". +// +// If the GCE_METADATA_HOST environment variable is not defined, a default of +// 169.254.169.254 will be used instead. +// +// If the requested metadata is not defined, the returned error will +// be of type NotDefinedError. +func (c *Client) Get(suffix string) (string, error) { + val, _, err := c.getETag(suffix) + return val, err +} + +func (c *Client) getTrimmed(suffix string) (s string, err error) { + s, err = c.Get(suffix) + s = strings.TrimSpace(s) + return +} + +func (c *Client) lines(suffix string) ([]string, error) { + j, err := c.Get(suffix) + if err != nil { + return nil, err + } + s := strings.Split(strings.TrimSpace(j), "\n") + for i := range s { + s[i] = strings.TrimSpace(s[i]) + } + return s, nil +} + +// ProjectID returns the current instance's project ID string. +func (c *Client) ProjectID() (string, error) { return projID.get(c) } + +// NumericProjectID returns the current instance's numeric project ID. +func (c *Client) NumericProjectID() (string, error) { return projNum.get(c) } + +// InstanceID returns the current VM's numeric instance ID. +func (c *Client) InstanceID() (string, error) { return instID.get(c) } + +// InternalIP returns the instance's primary internal IP address. +func (c *Client) InternalIP() (string, error) { + return c.getTrimmed("instance/network-interfaces/0/ip") +} + +// ExternalIP returns the instance's primary external (public) IP address. +func (c *Client) ExternalIP() (string, error) { + return c.getTrimmed("instance/network-interfaces/0/access-configs/0/external-ip") +} + +// Hostname returns the instance's hostname. This will be of the form +// ".c..internal". +func (c *Client) Hostname() (string, error) { + return c.getTrimmed("instance/hostname") +} + +// InstanceTags returns the list of user-defined instance tags, +// assigned when initially creating a GCE instance. +func (c *Client) InstanceTags() ([]string, error) { + var s []string + j, err := c.Get("instance/tags") + if err != nil { + return nil, err + } + if err := json.NewDecoder(strings.NewReader(j)).Decode(&s); err != nil { + return nil, err + } + return s, nil +} + +// InstanceName returns the current VM's instance ID string. +func (c *Client) InstanceName() (string, error) { + host, err := c.Hostname() + if err != nil { + return "", err + } + return strings.Split(host, ".")[0], nil +} + +// Zone returns the current VM's zone, such as "us-central1-b". +func (c *Client) Zone() (string, error) { + zone, err := c.getTrimmed("instance/zone") + // zone is of the form "projects//zones/". + if err != nil { + return "", err + } + return zone[strings.LastIndex(zone, "/")+1:], nil +} + +// InstanceAttributes returns the list of user-defined attributes, +// assigned when initially creating a GCE VM instance. The value of an +// attribute can be obtained with InstanceAttributeValue. +func (c *Client) InstanceAttributes() ([]string, error) { return c.lines("instance/attributes/") } + +// ProjectAttributes returns the list of user-defined attributes +// applying to the project as a whole, not just this VM. The value of +// an attribute can be obtained with ProjectAttributeValue. +func (c *Client) ProjectAttributes() ([]string, error) { return c.lines("project/attributes/") } + +// InstanceAttributeValue returns the value of the provided VM +// instance attribute. +// +// If the requested attribute is not defined, the returned error will +// be of type NotDefinedError. +// +// InstanceAttributeValue may return ("", nil) if the attribute was +// defined to be the empty string. +func (c *Client) InstanceAttributeValue(attr string) (string, error) { + return c.Get("instance/attributes/" + attr) +} + +// ProjectAttributeValue returns the value of the provided +// project attribute. +// +// If the requested attribute is not defined, the returned error will +// be of type NotDefinedError. +// +// ProjectAttributeValue may return ("", nil) if the attribute was +// defined to be the empty string. +func (c *Client) ProjectAttributeValue(attr string) (string, error) { + return c.Get("project/attributes/" + attr) +} + +// Scopes returns the service account scopes for the given account. +// The account may be empty or the string "default" to use the instance's +// main account. +func (c *Client) Scopes(serviceAccount string) ([]string, error) { + if serviceAccount == "" { + serviceAccount = "default" + } + return c.lines("instance/service-accounts/" + serviceAccount + "/scopes") +} + +// Subscribe subscribes to a value from the metadata service. +// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/". +// The suffix may contain query parameters. +// +// Subscribe calls fn with the latest metadata value indicated by the provided +// suffix. If the metadata value is deleted, fn is called with the empty string +// and ok false. Subscribe blocks until fn returns a non-nil error or the value +// is deleted. Subscribe returns the error value returned from the last call to +// fn, which may be nil when ok == false. +func (c *Client) Subscribe(suffix string, fn func(v string, ok bool) error) error { + const failedSubscribeSleep = time.Second * 5 + + // First check to see if the metadata value exists at all. + val, lastETag, err := c.getETag(suffix) + if err != nil { + return err + } + + if err := fn(val, true); err != nil { + return err + } + + ok := true + if strings.ContainsRune(suffix, '?') { + suffix += "&wait_for_change=true&last_etag=" + } else { + suffix += "?wait_for_change=true&last_etag=" + } + for { + val, etag, err := c.getETag(suffix + url.QueryEscape(lastETag)) + if err != nil { + if _, deleted := err.(NotDefinedError); !deleted { + time.Sleep(failedSubscribeSleep) + continue // Retry on other errors. + } + ok = false + } + lastETag = etag + + if err := fn(val, ok); err != nil || !ok { + return err + } + } +} + +// Error contains an error response from the server. +type Error struct { + // Code is the HTTP response status code. + Code int + // Message is the server response message. + Message string +} + +func (e *Error) Error() string { + return fmt.Sprintf("compute: Received %d `%s`", e.Code, e.Message) +} diff --git a/vendor/github.com/googleapis/gax-go/v2/LICENSE b/vendor/github.com/googleapis/gax-go/v2/LICENSE new file mode 100644 index 00000000..6d16b657 --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/v2/LICENSE @@ -0,0 +1,27 @@ +Copyright 2016, Google Inc. +All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/googleapis/gax-go/v2/call_option.go b/vendor/github.com/googleapis/gax-go/v2/call_option.go new file mode 100644 index 00000000..b1d53dd1 --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/v2/call_option.go @@ -0,0 +1,161 @@ +// Copyright 2016, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package gax + +import ( + "math/rand" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// CallOption is an option used by Invoke to control behaviors of RPC calls. +// CallOption works by modifying relevant fields of CallSettings. +type CallOption interface { + // Resolve applies the option by modifying cs. + Resolve(cs *CallSettings) +} + +// Retryer is used by Invoke to determine retry behavior. +type Retryer interface { + // Retry reports whether a request should be retriedand how long to pause before retrying + // if the previous attempt returned with err. Invoke never calls Retry with nil error. + Retry(err error) (pause time.Duration, shouldRetry bool) +} + +type retryerOption func() Retryer + +func (o retryerOption) Resolve(s *CallSettings) { + s.Retry = o +} + +// WithRetry sets CallSettings.Retry to fn. +func WithRetry(fn func() Retryer) CallOption { + return retryerOption(fn) +} + +// OnCodes returns a Retryer that retries if and only if +// the previous attempt returns a GRPC error whose error code is stored in cc. +// Pause times between retries are specified by bo. +// +// bo is only used for its parameters; each Retryer has its own copy. +func OnCodes(cc []codes.Code, bo Backoff) Retryer { + return &boRetryer{ + backoff: bo, + codes: append([]codes.Code(nil), cc...), + } +} + +type boRetryer struct { + backoff Backoff + codes []codes.Code +} + +func (r *boRetryer) Retry(err error) (time.Duration, bool) { + st, ok := status.FromError(err) + if !ok { + return 0, false + } + c := st.Code() + for _, rc := range r.codes { + if c == rc { + return r.backoff.Pause(), true + } + } + return 0, false +} + +// Backoff implements exponential backoff. +// The wait time between retries is a random value between 0 and the "retry envelope". +// The envelope starts at Initial and increases by the factor of Multiplier every retry, +// but is capped at Max. +type Backoff struct { + // Initial is the initial value of the retry envelope, defaults to 1 second. + Initial time.Duration + + // Max is the maximum value of the retry envelope, defaults to 30 seconds. + Max time.Duration + + // Multiplier is the factor by which the retry envelope increases. + // It should be greater than 1 and defaults to 2. + Multiplier float64 + + // cur is the current retry envelope + cur time.Duration +} + +// Pause returns the next time.Duration that the caller should use to backoff. +func (bo *Backoff) Pause() time.Duration { + if bo.Initial == 0 { + bo.Initial = time.Second + } + if bo.cur == 0 { + bo.cur = bo.Initial + } + if bo.Max == 0 { + bo.Max = 30 * time.Second + } + if bo.Multiplier < 1 { + bo.Multiplier = 2 + } + // Select a duration between 1ns and the current max. It might seem + // counterintuitive to have so much jitter, but + // https://www.awsarchitectureblog.com/2015/03/backoff.html argues that + // that is the best strategy. + d := time.Duration(1 + rand.Int63n(int64(bo.cur))) + bo.cur = time.Duration(float64(bo.cur) * bo.Multiplier) + if bo.cur > bo.Max { + bo.cur = bo.Max + } + return d +} + +type grpcOpt []grpc.CallOption + +func (o grpcOpt) Resolve(s *CallSettings) { + s.GRPC = o +} + +// WithGRPCOptions allows passing gRPC call options during client creation. +func WithGRPCOptions(opt ...grpc.CallOption) CallOption { + return grpcOpt(append([]grpc.CallOption(nil), opt...)) +} + +// CallSettings allow fine-grained control over how calls are made. +type CallSettings struct { + // Retry returns a Retryer to be used to control retry logic of a method call. + // If Retry is nil or the returned Retryer is nil, the call will not be retried. + Retry func() Retryer + + // CallOptions to be forwarded to GRPC. + GRPC []grpc.CallOption +} diff --git a/vendor/github.com/googleapis/gax-go/v2/gax.go b/vendor/github.com/googleapis/gax-go/v2/gax.go new file mode 100644 index 00000000..3fd1b0b8 --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/v2/gax.go @@ -0,0 +1,39 @@ +// Copyright 2016, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Package gax contains a set of modules which aid the development of APIs +// for clients and servers based on gRPC and Google API conventions. +// +// Application code will rarely need to use this library directly. +// However, code generated automatically from API definition files can use it +// to simplify code generation and to provide more convenient and idiomatic API surfaces. +package gax + +// Version specifies the gax-go version being used. +const Version = "2.0.4" diff --git a/vendor/github.com/googleapis/gax-go/v2/go.mod b/vendor/github.com/googleapis/gax-go/v2/go.mod new file mode 100644 index 00000000..9cdfaf44 --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/v2/go.mod @@ -0,0 +1,3 @@ +module github.com/googleapis/gax-go/v2 + +require google.golang.org/grpc v1.19.0 diff --git a/vendor/github.com/googleapis/gax-go/v2/go.sum b/vendor/github.com/googleapis/gax-go/v2/go.sum new file mode 100644 index 00000000..7fa23ecf --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/v2/go.sum @@ -0,0 +1,25 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d h1:g9qWBGx4puODJTMVyoPrpoxPFgVGd+z1DZwjfRu4d0I= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522 h1:Ve1ORMCxvRmSXBwJK+t3Oy+V2vRW2OetUQBq4rJIkZE= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/grpc v1.19.0 h1:cfg4PD8YEdSFnm7qLV4++93WcmhH2nIUhMjhdCvl3j8= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/vendor/github.com/googleapis/gax-go/v2/header.go b/vendor/github.com/googleapis/gax-go/v2/header.go new file mode 100644 index 00000000..139371a0 --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/v2/header.go @@ -0,0 +1,53 @@ +// Copyright 2018, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package gax + +import "bytes" + +// XGoogHeader is for use by the Google Cloud Libraries only. +// +// XGoogHeader formats key-value pairs. +// The resulting string is suitable for x-goog-api-client header. +func XGoogHeader(keyval ...string) string { + if len(keyval) == 0 { + return "" + } + if len(keyval)%2 != 0 { + panic("gax.Header: odd argument count") + } + var buf bytes.Buffer + for i := 0; i < len(keyval); i += 2 { + buf.WriteByte(' ') + buf.WriteString(keyval[i]) + buf.WriteByte('/') + buf.WriteString(keyval[i+1]) + } + return buf.String()[1:] +} diff --git a/vendor/github.com/googleapis/gax-go/v2/invoke.go b/vendor/github.com/googleapis/gax-go/v2/invoke.go new file mode 100644 index 00000000..fe31dd00 --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/v2/invoke.go @@ -0,0 +1,99 @@ +// Copyright 2016, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package gax + +import ( + "context" + "strings" + "time" +) + +// APICall is a user defined call stub. +type APICall func(context.Context, CallSettings) error + +// Invoke calls the given APICall, +// performing retries as specified by opts, if any. +func Invoke(ctx context.Context, call APICall, opts ...CallOption) error { + var settings CallSettings + for _, opt := range opts { + opt.Resolve(&settings) + } + return invoke(ctx, call, settings, Sleep) +} + +// Sleep is similar to time.Sleep, but it can be interrupted by ctx.Done() closing. +// If interrupted, Sleep returns ctx.Err(). +func Sleep(ctx context.Context, d time.Duration) error { + t := time.NewTimer(d) + select { + case <-ctx.Done(): + t.Stop() + return ctx.Err() + case <-t.C: + return nil + } +} + +type sleeper func(ctx context.Context, d time.Duration) error + +// invoke implements Invoke, taking an additional sleeper argument for testing. +func invoke(ctx context.Context, call APICall, settings CallSettings, sp sleeper) error { + var retryer Retryer + for { + err := call(ctx, settings) + if err == nil { + return nil + } + if settings.Retry == nil { + return err + } + // Never retry permanent certificate errors. (e.x. if ca-certificates + // are not installed). We should only make very few, targeted + // exceptions: many (other) status=Unavailable should be retried, such + // as if there's a network hiccup, or the internet goes out for a + // minute. This is also why here we are doing string parsing instead of + // simply making Unavailable a non-retried code elsewhere. + if strings.Contains(err.Error(), "x509: certificate signed by unknown authority") { + return err + } + if retryer == nil { + if r := settings.Retry(); r != nil { + retryer = r + } else { + return err + } + } + if d, ok := retryer.Retry(err); !ok { + return err + } else if err = sp(ctx, d); err != nil { + return err + } + } +} diff --git a/vendor/github.com/hashicorp/golang-lru/LICENSE b/vendor/github.com/hashicorp/golang-lru/LICENSE new file mode 100644 index 00000000..be2cc4df --- /dev/null +++ b/vendor/github.com/hashicorp/golang-lru/LICENSE @@ -0,0 +1,362 @@ +Mozilla Public License, version 2.0 + +1. Definitions + +1.1. "Contributor" + + means each individual or legal entity that creates, contributes to the + creation of, or owns Covered Software. + +1.2. "Contributor Version" + + means the combination of the Contributions of others (if any) used by a + Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + + means Source Code Form to which the initial Contributor has attached the + notice in Exhibit A, the Executable Form of such Source Code Form, and + Modifications of such Source Code Form, in each case including portions + thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + a. that the initial Contributor has attached the notice described in + Exhibit B to the Covered Software; or + + b. that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the terms of + a Secondary License. + +1.6. "Executable Form" + + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + + means a work that combines Covered Software with other material, in a + separate file or files, that is not Covered Software. + +1.8. "License" + + means this document. + +1.9. "Licensable" + + means having the right to grant, to the maximum extent possible, whether + at the time of the initial grant or subsequently, any and all of the + rights conveyed by this License. + +1.10. "Modifications" + + means any of the following: + + a. any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered Software; or + + b. any new file in Source Code Form that contains any Covered Software. + +1.11. "Patent Claims" of a Contributor + + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the License, + by the making, using, selling, offering for sale, having made, import, + or transfer of either its Contributions or its Contributor Version. + +1.12. "Secondary License" + + means either the GNU General Public License, Version 2.0, the GNU Lesser + General Public License, Version 2.1, the GNU Affero General Public + License, Version 3.0, or any later versions of those licenses. + +1.13. "Source Code Form" + + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that controls, is + controlled by, or is under common control with You. For purposes of this + definition, "control" means (a) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (b) ownership of more than fifty percent (50%) of the + outstanding shares or beneficial ownership of such entity. + + +2. License Grants and Conditions + +2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + a. under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + + b. under Patent Claims of such Contributor to make, use, sell, offer for + sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution + become effective for each Contribution on the date the Contributor first + distributes such Contribution. + +2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under + this License. No additional rights or licenses will be implied from the + distribution or licensing of Covered Software under this License. + Notwithstanding Section 2.1(b) above, no patent license is granted by a + Contributor: + + a. for any code that a Contributor has removed from Covered Software; or + + b. for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + + c. under Patent Claims infringed by Covered Software in the absence of + its Contributions. + + This License does not grant any rights in the trademarks, service marks, + or logos of any Contributor (except as may be necessary to comply with + the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to + distribute the Covered Software under a subsequent version of this + License (see Section 10.2) or under the terms of a Secondary License (if + permitted under the terms of Section 3.3). + +2.5. Representation + + Each Contributor represents that the Contributor believes its + Contributions are its original creation(s) or it has sufficient rights to + grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + + This License is not intended to limit any rights You have under + applicable copyright doctrines of fair use, fair dealing, or other + equivalents. + +2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in + Section 2.1. + + +3. Responsibilities + +3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any + Modifications that You create or to which You contribute, must be under + the terms of this License. You must inform recipients that the Source + Code Form of the Covered Software is governed by the terms of this + License, and how they can obtain a copy of this License. You may not + attempt to alter or restrict the recipients' rights in the Source Code + Form. + +3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + a. such Covered Software must also be made available in Source Code Form, + as described in Section 3.1, and You must inform recipients of the + Executable Form how they can obtain a copy of such Source Code Form by + reasonable means in a timely manner, at a charge no more than the cost + of distribution to the recipient; and + + b. You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter the + recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, + provided that You also comply with the requirements of this License for + the Covered Software. If the Larger Work is a combination of Covered + Software with a work governed by one or more Secondary Licenses, and the + Covered Software is not Incompatible With Secondary Licenses, this + License permits You to additionally distribute such Covered Software + under the terms of such Secondary License(s), so that the recipient of + the Larger Work may, at their option, further distribute the Covered + Software under the terms of either this License or such Secondary + License(s). + +3.4. Notices + + You may not remove or alter the substance of any license notices + (including copyright notices, patent notices, disclaimers of warranty, or + limitations of liability) contained within the Source Code Form of the + Covered Software, except that You may alter any license notices to the + extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, + indemnity or liability obligations to one or more recipients of Covered + Software. However, You may do so only on Your own behalf, and not on + behalf of any Contributor. You must make it absolutely clear that any + such warranty, support, indemnity, or liability obligation is offered by + You alone, and You hereby agree to indemnify every Contributor for any + liability incurred by such Contributor as a result of warranty, support, + indemnity or liability terms You offer. You may include additional + disclaimers of warranty and limitations of liability specific to any + jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License + with respect to some or all of the Covered Software due to statute, + judicial order, or regulation then You must: (a) comply with the terms of + this License to the maximum extent possible; and (b) describe the + limitations and the code they affect. Such description must be placed in a + text file included with all distributions of the Covered Software under + this License. Except to the extent prohibited by statute or regulation, + such description must be sufficiently detailed for a recipient of ordinary + skill to be able to understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You + fail to comply with any of its terms. However, if You become compliant, + then the rights granted under this License from a particular Contributor + are reinstated (a) provisionally, unless and until such Contributor + explicitly and finally terminates Your grants, and (b) on an ongoing + basis, if such Contributor fails to notify You of the non-compliance by + some reasonable means prior to 60 days after You have come back into + compliance. Moreover, Your grants from a particular Contributor are + reinstated on an ongoing basis if such Contributor notifies You of the + non-compliance by some reasonable means, this is the first time You have + received notice of non-compliance with this License from such + Contributor, and You become compliant prior to 30 days after Your receipt + of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent + infringement claim (excluding declaratory judgment actions, + counter-claims, and cross-claims) alleging that a Contributor Version + directly or indirectly infringes any patent, then the rights granted to + You by any and all Contributors for the Covered Software under Section + 2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user + license agreements (excluding distributors and resellers) which have been + validly granted by You or Your distributors under this License prior to + termination shall survive termination. + +6. Disclaimer of Warranty + + Covered Software is provided under this License on an "as is" basis, + without warranty of any kind, either expressed, implied, or statutory, + including, without limitation, warranties that the Covered Software is free + of defects, merchantable, fit for a particular purpose or non-infringing. + The entire risk as to the quality and performance of the Covered Software + is with You. Should any Covered Software prove defective in any respect, + You (not any Contributor) assume the cost of any necessary servicing, + repair, or correction. This disclaimer of warranty constitutes an essential + part of this License. No use of any Covered Software is authorized under + this License except under this disclaimer. + +7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including + negligence), contract, or otherwise, shall any Contributor, or anyone who + distributes Covered Software as permitted above, be liable to You for any + direct, indirect, special, incidental, or consequential damages of any + character including, without limitation, damages for lost profits, loss of + goodwill, work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses, even if such party shall have been + informed of the possibility of such damages. This limitation of liability + shall not apply to liability for death or personal injury resulting from + such party's negligence to the extent applicable law prohibits such + limitation. Some jurisdictions do not allow the exclusion or limitation of + incidental or consequential damages, so this exclusion and limitation may + not apply to You. + +8. Litigation + + Any litigation relating to this License may be brought only in the courts + of a jurisdiction where the defendant maintains its principal place of + business and such litigation shall be governed by laws of that + jurisdiction, without reference to its conflict-of-law provisions. Nothing + in this Section shall prevent a party's ability to bring cross-claims or + counter-claims. + +9. Miscellaneous + + This License represents the complete agreement concerning the subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. Any law or regulation which provides that + the language of a contract shall be construed against the drafter shall not + be used to construe this License against a Contributor. + + +10. Versions of the License + +10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section + 10.3, no one other than the license steward has the right to modify or + publish new versions of this License. Each version will be given a + distinguishing version number. + +10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version + of the License under which You originally received the Covered Software, + or under the terms of any subsequent version published by the license + steward. + +10.3. Modified Versions + + If you create software not governed by this License, and you want to + create a new license for such software, you may create and use a + modified version of this License if you rename the license and remove + any references to the name of the license steward (except to note that + such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary + Licenses If You choose to distribute Source Code Form that is + Incompatible With Secondary Licenses under the terms of this version of + the License, the notice described in Exhibit B of this License must be + attached. + +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the + terms of the Mozilla Public License, v. + 2.0. If a copy of the MPL was not + distributed with this file, You can + obtain one at + http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, +then You may include the notice in a location (such as a LICENSE file in a +relevant directory) where a recipient would be likely to look for such a +notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice + + This Source Code Form is "Incompatible + With Secondary Licenses", as defined by + the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go b/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go new file mode 100644 index 00000000..5673773b --- /dev/null +++ b/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go @@ -0,0 +1,161 @@ +package simplelru + +import ( + "container/list" + "errors" +) + +// EvictCallback is used to get a callback when a cache entry is evicted +type EvictCallback func(key interface{}, value interface{}) + +// LRU implements a non-thread safe fixed size LRU cache +type LRU struct { + size int + evictList *list.List + items map[interface{}]*list.Element + onEvict EvictCallback +} + +// entry is used to hold a value in the evictList +type entry struct { + key interface{} + value interface{} +} + +// NewLRU constructs an LRU of the given size +func NewLRU(size int, onEvict EvictCallback) (*LRU, error) { + if size <= 0 { + return nil, errors.New("Must provide a positive size") + } + c := &LRU{ + size: size, + evictList: list.New(), + items: make(map[interface{}]*list.Element), + onEvict: onEvict, + } + return c, nil +} + +// Purge is used to completely clear the cache. +func (c *LRU) Purge() { + for k, v := range c.items { + if c.onEvict != nil { + c.onEvict(k, v.Value.(*entry).value) + } + delete(c.items, k) + } + c.evictList.Init() +} + +// Add adds a value to the cache. Returns true if an eviction occurred. +func (c *LRU) Add(key, value interface{}) (evicted bool) { + // Check for existing item + if ent, ok := c.items[key]; ok { + c.evictList.MoveToFront(ent) + ent.Value.(*entry).value = value + return false + } + + // Add new item + ent := &entry{key, value} + entry := c.evictList.PushFront(ent) + c.items[key] = entry + + evict := c.evictList.Len() > c.size + // Verify size not exceeded + if evict { + c.removeOldest() + } + return evict +} + +// Get looks up a key's value from the cache. +func (c *LRU) Get(key interface{}) (value interface{}, ok bool) { + if ent, ok := c.items[key]; ok { + c.evictList.MoveToFront(ent) + return ent.Value.(*entry).value, true + } + return +} + +// Contains checks if a key is in the cache, without updating the recent-ness +// or deleting it for being stale. +func (c *LRU) Contains(key interface{}) (ok bool) { + _, ok = c.items[key] + return ok +} + +// Peek returns the key value (or undefined if not found) without updating +// the "recently used"-ness of the key. +func (c *LRU) Peek(key interface{}) (value interface{}, ok bool) { + var ent *list.Element + if ent, ok = c.items[key]; ok { + return ent.Value.(*entry).value, true + } + return nil, ok +} + +// Remove removes the provided key from the cache, returning if the +// key was contained. +func (c *LRU) Remove(key interface{}) (present bool) { + if ent, ok := c.items[key]; ok { + c.removeElement(ent) + return true + } + return false +} + +// RemoveOldest removes the oldest item from the cache. +func (c *LRU) RemoveOldest() (key interface{}, value interface{}, ok bool) { + ent := c.evictList.Back() + if ent != nil { + c.removeElement(ent) + kv := ent.Value.(*entry) + return kv.key, kv.value, true + } + return nil, nil, false +} + +// GetOldest returns the oldest entry +func (c *LRU) GetOldest() (key interface{}, value interface{}, ok bool) { + ent := c.evictList.Back() + if ent != nil { + kv := ent.Value.(*entry) + return kv.key, kv.value, true + } + return nil, nil, false +} + +// Keys returns a slice of the keys in the cache, from oldest to newest. +func (c *LRU) Keys() []interface{} { + keys := make([]interface{}, len(c.items)) + i := 0 + for ent := c.evictList.Back(); ent != nil; ent = ent.Prev() { + keys[i] = ent.Value.(*entry).key + i++ + } + return keys +} + +// Len returns the number of items in the cache. +func (c *LRU) Len() int { + return c.evictList.Len() +} + +// removeOldest removes the oldest item from the cache. +func (c *LRU) removeOldest() { + ent := c.evictList.Back() + if ent != nil { + c.removeElement(ent) + } +} + +// removeElement is used to remove a given list element from the cache +func (c *LRU) removeElement(e *list.Element) { + c.evictList.Remove(e) + kv := e.Value.(*entry) + delete(c.items, kv.key) + if c.onEvict != nil { + c.onEvict(kv.key, kv.value) + } +} diff --git a/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go b/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go new file mode 100644 index 00000000..74c70774 --- /dev/null +++ b/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go @@ -0,0 +1,36 @@ +package simplelru + +// LRUCache is the interface for simple LRU cache. +type LRUCache interface { + // Adds a value to the cache, returns true if an eviction occurred and + // updates the "recently used"-ness of the key. + Add(key, value interface{}) bool + + // Returns key's value from the cache and + // updates the "recently used"-ness of the key. #value, isFound + Get(key interface{}) (value interface{}, ok bool) + + // Check if a key exsists in cache without updating the recent-ness. + Contains(key interface{}) (ok bool) + + // Returns key's value without updating the "recently used"-ness of the key. + Peek(key interface{}) (value interface{}, ok bool) + + // Removes a key from the cache. + Remove(key interface{}) bool + + // Removes the oldest entry from cache. + RemoveOldest() (interface{}, interface{}, bool) + + // Returns the oldest entry from the cache. #key, value, isFound + GetOldest() (interface{}, interface{}, bool) + + // Returns a slice of the keys in the cache, from oldest to newest. + Keys() []interface{} + + // Returns the number of items in the cache. + Len() int + + // Clear all cache entries + Purge() +} diff --git a/vendor/go.opencensus.io/.gitignore b/vendor/go.opencensus.io/.gitignore new file mode 100644 index 00000000..74a6db47 --- /dev/null +++ b/vendor/go.opencensus.io/.gitignore @@ -0,0 +1,9 @@ +/.idea/ + +# go.opencensus.io/exporter/aws +/exporter/aws/ + +# Exclude vendor, use dep ensure after checkout: +/vendor/github.com/ +/vendor/golang.org/ +/vendor/google.golang.org/ diff --git a/vendor/go.opencensus.io/.travis.yml b/vendor/go.opencensus.io/.travis.yml new file mode 100644 index 00000000..bd6b66ee --- /dev/null +++ b/vendor/go.opencensus.io/.travis.yml @@ -0,0 +1,17 @@ +language: go + +go_import_path: go.opencensus.io + +go: + - 1.11.x + +env: + global: + GO111MODULE=on + +before_script: + - make install-tools + +script: + - make travis-ci + - go run internal/check/version.go # TODO move this to makefile diff --git a/vendor/go.opencensus.io/AUTHORS b/vendor/go.opencensus.io/AUTHORS new file mode 100644 index 00000000..e491a9e7 --- /dev/null +++ b/vendor/go.opencensus.io/AUTHORS @@ -0,0 +1 @@ +Google Inc. diff --git a/vendor/go.opencensus.io/CONTRIBUTING.md b/vendor/go.opencensus.io/CONTRIBUTING.md new file mode 100644 index 00000000..1ba3962c --- /dev/null +++ b/vendor/go.opencensus.io/CONTRIBUTING.md @@ -0,0 +1,63 @@ +# How to contribute + +We'd love to accept your patches and contributions to this project. There are +just a few small guidelines you need to follow. + +## Contributor License Agreement + +Contributions to this project must be accompanied by a Contributor License +Agreement. You (or your employer) retain the copyright to your contribution, +this simply gives us permission to use and redistribute your contributions as +part of the project. Head over to to see +your current agreements on file or to sign a new one. + +You generally only need to submit a CLA once, so if you've already submitted one +(even if it was for a different project), you probably don't need to do it +again. + +## Code reviews + +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. Consult [GitHub Help] for more +information on using pull requests. + +[GitHub Help]: https://help.github.com/articles/about-pull-requests/ + +## Instructions + +Fork the repo, checkout the upstream repo to your GOPATH by: + +``` +$ go get -d go.opencensus.io +``` + +Add your fork as an origin: + +``` +cd $(go env GOPATH)/src/go.opencensus.io +git remote add fork git@github.com:YOUR_GITHUB_USERNAME/opencensus-go.git +``` + +Run tests: + +``` +$ make install-tools # Only first time. +$ make +``` + +Checkout a new branch, make modifications and push the branch to your fork: + +``` +$ git checkout -b feature +# edit files +$ git commit +$ git push fork feature +``` + +Open a pull request against the main opencensus-go repo. + +## General Notes +This project uses Appveyor and Travis for CI. + +The dependencies are managed with `go mod` if you work with the sources under your +`$GOPATH` you need to set the environment variable `GO111MODULE=on`. \ No newline at end of file diff --git a/vendor/go.opencensus.io/Gopkg.lock b/vendor/go.opencensus.io/Gopkg.lock new file mode 100644 index 00000000..3be12ac8 --- /dev/null +++ b/vendor/go.opencensus.io/Gopkg.lock @@ -0,0 +1,231 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + branch = "master" + digest = "1:eee9386329f4fcdf8d6c0def0c9771b634bdd5ba460d888aa98c17d59b37a76c" + name = "git.apache.org/thrift.git" + packages = ["lib/go/thrift"] + pruneopts = "UT" + revision = "6e67faa92827ece022380b211c2caaadd6145bf5" + source = "github.com/apache/thrift" + +[[projects]] + branch = "master" + digest = "1:d6afaeed1502aa28e80a4ed0981d570ad91b2579193404256ce672ed0a609e0d" + name = "github.com/beorn7/perks" + packages = ["quantile"] + pruneopts = "UT" + revision = "3a771d992973f24aa725d07868b467d1ddfceafb" + +[[projects]] + digest = "1:4c0989ca0bcd10799064318923b9bc2db6b4d6338dd75f3f2d86c3511aaaf5cf" + name = "github.com/golang/protobuf" + packages = [ + "proto", + "ptypes", + "ptypes/any", + "ptypes/duration", + "ptypes/timestamp", + ] + pruneopts = "UT" + revision = "aa810b61a9c79d51363740d207bb46cf8e620ed5" + version = "v1.2.0" + +[[projects]] + digest = "1:ff5ebae34cfbf047d505ee150de27e60570e8c394b3b8fdbb720ff6ac71985fc" + name = "github.com/matttproud/golang_protobuf_extensions" + packages = ["pbutil"] + pruneopts = "UT" + revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" + version = "v1.0.1" + +[[projects]] + digest = "1:824c8f3aa4c5f23928fa84ebbd5ed2e9443b3f0cb958a40c1f2fbed5cf5e64b1" + name = "github.com/openzipkin/zipkin-go" + packages = [ + ".", + "idgenerator", + "model", + "propagation", + "reporter", + "reporter/http", + ] + pruneopts = "UT" + revision = "d455a5674050831c1e187644faa4046d653433c2" + version = "v0.1.1" + +[[projects]] + digest = "1:d14a5f4bfecf017cb780bdde1b6483e5deb87e12c332544d2c430eda58734bcb" + name = "github.com/prometheus/client_golang" + packages = [ + "prometheus", + "prometheus/promhttp", + ] + pruneopts = "UT" + revision = "c5b7fccd204277076155f10851dad72b76a49317" + version = "v0.8.0" + +[[projects]] + branch = "master" + digest = "1:2d5cd61daa5565187e1d96bae64dbbc6080dacf741448e9629c64fd93203b0d4" + name = "github.com/prometheus/client_model" + packages = ["go"] + pruneopts = "UT" + revision = "5c3871d89910bfb32f5fcab2aa4b9ec68e65a99f" + +[[projects]] + branch = "master" + digest = "1:63b68062b8968092eb86bedc4e68894bd096ea6b24920faca8b9dcf451f54bb5" + name = "github.com/prometheus/common" + packages = [ + "expfmt", + "internal/bitbucket.org/ww/goautoneg", + "model", + ] + pruneopts = "UT" + revision = "c7de2306084e37d54b8be01f3541a8464345e9a5" + +[[projects]] + branch = "master" + digest = "1:8c49953a1414305f2ff5465147ee576dd705487c35b15918fcd4efdc0cb7a290" + name = "github.com/prometheus/procfs" + packages = [ + ".", + "internal/util", + "nfs", + "xfs", + ] + pruneopts = "UT" + revision = "05ee40e3a273f7245e8777337fc7b46e533a9a92" + +[[projects]] + branch = "master" + digest = "1:deafe4ab271911fec7de5b693d7faae3f38796d9eb8622e2b9e7df42bb3dfea9" + name = "golang.org/x/net" + packages = [ + "context", + "http/httpguts", + "http2", + "http2/hpack", + "idna", + "internal/timeseries", + "trace", + ] + pruneopts = "UT" + revision = "922f4815f713f213882e8ef45e0d315b164d705c" + +[[projects]] + branch = "master" + digest = "1:e0140c0c868c6e0f01c0380865194592c011fe521d6e12d78bfd33e756fe018a" + name = "golang.org/x/sync" + packages = ["semaphore"] + pruneopts = "UT" + revision = "1d60e4601c6fd243af51cc01ddf169918a5407ca" + +[[projects]] + branch = "master" + digest = "1:a3f00ac457c955fe86a41e1495e8f4c54cb5399d609374c5cc26aa7d72e542c8" + name = "golang.org/x/sys" + packages = ["unix"] + pruneopts = "UT" + revision = "3b58ed4ad3395d483fc92d5d14123ce2c3581fec" + +[[projects]] + digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" + name = "golang.org/x/text" + packages = [ + "collate", + "collate/build", + "internal/colltab", + "internal/gen", + "internal/tag", + "internal/triegen", + "internal/ucd", + "language", + "secure/bidirule", + "transform", + "unicode/bidi", + "unicode/cldr", + "unicode/norm", + "unicode/rangetable", + ] + pruneopts = "UT" + revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" + version = "v0.3.0" + +[[projects]] + branch = "master" + digest = "1:c0c17c94fe8bc1ab34e7f586a4a8b788c5e1f4f9f750ff23395b8b2f5a523530" + name = "google.golang.org/api" + packages = ["support/bundler"] + pruneopts = "UT" + revision = "e21acd801f91da814261b938941d193bb036441a" + +[[projects]] + branch = "master" + digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c" + name = "google.golang.org/genproto" + packages = ["googleapis/rpc/status"] + pruneopts = "UT" + revision = "c66870c02cf823ceb633bcd05be3c7cda29976f4" + +[[projects]] + digest = "1:3dd7996ce6bf52dec6a2f69fa43e7c4cefea1d4dfa3c8ab7a5f8a9f7434e239d" + name = "google.golang.org/grpc" + packages = [ + ".", + "balancer", + "balancer/base", + "balancer/roundrobin", + "codes", + "connectivity", + "credentials", + "encoding", + "encoding/proto", + "grpclog", + "internal", + "internal/backoff", + "internal/channelz", + "internal/envconfig", + "internal/grpcrand", + "internal/transport", + "keepalive", + "metadata", + "naming", + "peer", + "resolver", + "resolver/dns", + "resolver/passthrough", + "stats", + "status", + "tap", + ] + pruneopts = "UT" + revision = "32fb0ac620c32ba40a4626ddf94d90d12cce3455" + version = "v1.14.0" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + input-imports = [ + "git.apache.org/thrift.git/lib/go/thrift", + "github.com/golang/protobuf/proto", + "github.com/openzipkin/zipkin-go", + "github.com/openzipkin/zipkin-go/model", + "github.com/openzipkin/zipkin-go/reporter", + "github.com/openzipkin/zipkin-go/reporter/http", + "github.com/prometheus/client_golang/prometheus", + "github.com/prometheus/client_golang/prometheus/promhttp", + "golang.org/x/net/context", + "golang.org/x/net/http2", + "google.golang.org/api/support/bundler", + "google.golang.org/grpc", + "google.golang.org/grpc/codes", + "google.golang.org/grpc/grpclog", + "google.golang.org/grpc/metadata", + "google.golang.org/grpc/stats", + "google.golang.org/grpc/status", + ] + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/vendor/go.opencensus.io/Gopkg.toml b/vendor/go.opencensus.io/Gopkg.toml new file mode 100644 index 00000000..a9f3cd68 --- /dev/null +++ b/vendor/go.opencensus.io/Gopkg.toml @@ -0,0 +1,36 @@ +# For v0.x.y dependencies, prefer adding a constraints of the form: version=">= 0.x.y" +# to avoid locking to a particular minor version which can cause dep to not be +# able to find a satisfying dependency graph. + +[[constraint]] + branch = "master" + name = "git.apache.org/thrift.git" + source = "github.com/apache/thrift" + +[[constraint]] + name = "github.com/golang/protobuf" + version = "1.0.0" + +[[constraint]] + name = "github.com/openzipkin/zipkin-go" + version = ">=0.1.0" + +[[constraint]] + name = "github.com/prometheus/client_golang" + version = ">=0.8.0" + +[[constraint]] + branch = "master" + name = "golang.org/x/net" + +[[constraint]] + branch = "master" + name = "google.golang.org/api" + +[[constraint]] + name = "google.golang.org/grpc" + version = "1.11.3" + +[prune] + go-tests = true + unused-packages = true diff --git a/vendor/go.opencensus.io/LICENSE b/vendor/go.opencensus.io/LICENSE new file mode 100644 index 00000000..7a4a3ea2 --- /dev/null +++ b/vendor/go.opencensus.io/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/vendor/go.opencensus.io/Makefile b/vendor/go.opencensus.io/Makefile new file mode 100644 index 00000000..457866cb --- /dev/null +++ b/vendor/go.opencensus.io/Makefile @@ -0,0 +1,96 @@ +# TODO: Fix this on windows. +ALL_SRC := $(shell find . -name '*.go' \ + -not -path './vendor/*' \ + -not -path '*/gen-go/*' \ + -type f | sort) +ALL_PKGS := $(shell go list $(sort $(dir $(ALL_SRC)))) + +GOTEST_OPT?=-v -race -timeout 30s +GOTEST_OPT_WITH_COVERAGE = $(GOTEST_OPT) -coverprofile=coverage.txt -covermode=atomic +GOTEST=go test +GOFMT=gofmt +GOLINT=golint +GOVET=go vet +EMBEDMD=embedmd +# TODO decide if we need to change these names. +TRACE_ID_LINT_EXCEPTION="type name will be used as trace.TraceID by other packages" +TRACE_OPTION_LINT_EXCEPTION="type name will be used as trace.TraceOptions by other packages" +README_FILES := $(shell find . -name '*README.md' | sort | tr '\n' ' ') + +.DEFAULT_GOAL := fmt-lint-vet-embedmd-test + +.PHONY: fmt-lint-vet-embedmd-test +fmt-lint-vet-embedmd-test: fmt lint vet embedmd test + +# TODO enable test-with-coverage in tavis +.PHONY: travis-ci +travis-ci: fmt lint vet embedmd test test-386 + +all-pkgs: + @echo $(ALL_PKGS) | tr ' ' '\n' | sort + +all-srcs: + @echo $(ALL_SRC) | tr ' ' '\n' | sort + +.PHONY: test +test: + $(GOTEST) $(GOTEST_OPT) $(ALL_PKGS) + +.PHONY: test-386 +test-386: + GOARCH=386 $(GOTEST) -v -timeout 30s $(ALL_PKGS) + +.PHONY: test-with-coverage +test-with-coverage: + $(GOTEST) $(GOTEST_OPT_WITH_COVERAGE) $(ALL_PKGS) + +.PHONY: fmt +fmt: + @FMTOUT=`$(GOFMT) -s -l $(ALL_SRC) 2>&1`; \ + if [ "$$FMTOUT" ]; then \ + echo "$(GOFMT) FAILED => gofmt the following files:\n"; \ + echo "$$FMTOUT\n"; \ + exit 1; \ + else \ + echo "Fmt finished successfully"; \ + fi + +.PHONY: lint +lint: + @LINTOUT=`$(GOLINT) $(ALL_PKGS) | grep -v $(TRACE_ID_LINT_EXCEPTION) | grep -v $(TRACE_OPTION_LINT_EXCEPTION) 2>&1`; \ + if [ "$$LINTOUT" ]; then \ + echo "$(GOLINT) FAILED => clean the following lint errors:\n"; \ + echo "$$LINTOUT\n"; \ + exit 1; \ + else \ + echo "Lint finished successfully"; \ + fi + +.PHONY: vet +vet: + # TODO: Understand why go vet downloads "github.com/google/go-cmp v0.2.0" + @VETOUT=`$(GOVET) ./... | grep -v "go: downloading" 2>&1`; \ + if [ "$$VETOUT" ]; then \ + echo "$(GOVET) FAILED => go vet the following files:\n"; \ + echo "$$VETOUT\n"; \ + exit 1; \ + else \ + echo "Vet finished successfully"; \ + fi + +.PHONY: embedmd +embedmd: + @EMBEDMDOUT=`$(EMBEDMD) -d $(README_FILES) 2>&1`; \ + if [ "$$EMBEDMDOUT" ]; then \ + echo "$(EMBEDMD) FAILED => embedmd the following files:\n"; \ + echo "$$EMBEDMDOUT\n"; \ + exit 1; \ + else \ + echo "Embedmd finished successfully"; \ + fi + +.PHONY: install-tools +install-tools: + go get -u golang.org/x/tools/cmd/cover + go get -u golang.org/x/lint/golint + go get -u github.com/rakyll/embedmd diff --git a/vendor/go.opencensus.io/README.md b/vendor/go.opencensus.io/README.md new file mode 100644 index 00000000..3f40ed5c --- /dev/null +++ b/vendor/go.opencensus.io/README.md @@ -0,0 +1,263 @@ +# OpenCensus Libraries for Go + +[![Build Status][travis-image]][travis-url] +[![Windows Build Status][appveyor-image]][appveyor-url] +[![GoDoc][godoc-image]][godoc-url] +[![Gitter chat][gitter-image]][gitter-url] + +OpenCensus Go is a Go implementation of OpenCensus, a toolkit for +collecting application performance and behavior monitoring data. +Currently it consists of three major components: tags, stats and tracing. + +## Installation + +``` +$ go get -u go.opencensus.io +``` + +The API of this project is still evolving, see: [Deprecation Policy](#deprecation-policy). +The use of vendoring or a dependency management tool is recommended. + +## Prerequisites + +OpenCensus Go libraries require Go 1.8 or later. + +## Getting Started + +The easiest way to get started using OpenCensus in your application is to use an existing +integration with your RPC framework: + +* [net/http](https://godoc.org/go.opencensus.io/plugin/ochttp) +* [gRPC](https://godoc.org/go.opencensus.io/plugin/ocgrpc) +* [database/sql](https://godoc.org/github.com/opencensus-integrations/ocsql) +* [Go kit](https://godoc.org/github.com/go-kit/kit/tracing/opencensus) +* [Groupcache](https://godoc.org/github.com/orijtech/groupcache) +* [Caddy webserver](https://godoc.org/github.com/orijtech/caddy) +* [MongoDB](https://godoc.org/github.com/orijtech/mongo-go-driver) +* [Redis gomodule/redigo](https://godoc.org/github.com/orijtech/redigo) +* [Redis goredis/redis](https://godoc.org/github.com/orijtech/redis) +* [Memcache](https://godoc.org/github.com/orijtech/gomemcache) + +If you're using a framework not listed here, you could either implement your own middleware for your +framework or use [custom stats](#stats) and [spans](#spans) directly in your application. + +## Exporters + +OpenCensus can export instrumentation data to various backends. +OpenCensus has exporter implementations for the following, users +can implement their own exporters by implementing the exporter interfaces +([stats](https://godoc.org/go.opencensus.io/stats/view#Exporter), +[trace](https://godoc.org/go.opencensus.io/trace#Exporter)): + +* [Prometheus][exporter-prom] for stats +* [OpenZipkin][exporter-zipkin] for traces +* [Stackdriver][exporter-stackdriver] Monitoring for stats and Trace for traces +* [Jaeger][exporter-jaeger] for traces +* [AWS X-Ray][exporter-xray] for traces +* [Datadog][exporter-datadog] for stats and traces +* [Graphite][exporter-graphite] for stats +* [Honeycomb][exporter-honeycomb] for traces + +## Overview + +![OpenCensus Overview](https://i.imgur.com/cf4ElHE.jpg) + +In a microservices environment, a user request may go through +multiple services until there is a response. OpenCensus allows +you to instrument your services and collect diagnostics data all +through your services end-to-end. + +## Tags + +Tags represent propagated key-value pairs. They are propagated using `context.Context` +in the same process or can be encoded to be transmitted on the wire. Usually, this will +be handled by an integration plugin, e.g. `ocgrpc.ServerHandler` and `ocgrpc.ClientHandler` +for gRPC. + +Package `tag` allows adding or modifying tags in the current context. + +[embedmd]:# (internal/readme/tags.go new) +```go +ctx, err = tag.New(ctx, + tag.Insert(osKey, "macOS-10.12.5"), + tag.Upsert(userIDKey, "cde36753ed"), +) +if err != nil { + log.Fatal(err) +} +``` + +## Stats + +OpenCensus is a low-overhead framework even if instrumentation is always enabled. +In order to be so, it is optimized to make recording of data points fast +and separate from the data aggregation. + +OpenCensus stats collection happens in two stages: + +* Definition of measures and recording of data points +* Definition of views and aggregation of the recorded data + +### Recording + +Measurements are data points associated with a measure. +Recording implicitly tags the set of Measurements with the tags from the +provided context: + +[embedmd]:# (internal/readme/stats.go record) +```go +stats.Record(ctx, videoSize.M(102478)) +``` + +### Views + +Views are how Measures are aggregated. You can think of them as queries over the +set of recorded data points (measurements). + +Views have two parts: the tags to group by and the aggregation type used. + +Currently three types of aggregations are supported: +* CountAggregation is used to count the number of times a sample was recorded. +* DistributionAggregation is used to provide a histogram of the values of the samples. +* SumAggregation is used to sum up all sample values. + +[embedmd]:# (internal/readme/stats.go aggs) +```go +distAgg := view.Distribution(1<<32, 2<<32, 3<<32) +countAgg := view.Count() +sumAgg := view.Sum() +``` + +Here we create a view with the DistributionAggregation over our measure. + +[embedmd]:# (internal/readme/stats.go view) +```go +if err := view.Register(&view.View{ + Name: "example.com/video_size_distribution", + Description: "distribution of processed video size over time", + Measure: videoSize, + Aggregation: view.Distribution(1<<32, 2<<32, 3<<32), +}); err != nil { + log.Fatalf("Failed to register view: %v", err) +} +``` + +Register begins collecting data for the view. Registered views' data will be +exported via the registered exporters. + +## Traces + +A distributed trace tracks the progression of a single user request as +it is handled by the services and processes that make up an application. +Each step is called a span in the trace. Spans include metadata about the step, +including especially the time spent in the step, called the span’s latency. + +Below you see a trace and several spans underneath it. + +![Traces and spans](https://i.imgur.com/7hZwRVj.png) + +### Spans + +Span is the unit step in a trace. Each span has a name, latency, status and +additional metadata. + +Below we are starting a span for a cache read and ending it +when we are done: + +[embedmd]:# (internal/readme/trace.go startend) +```go +ctx, span := trace.StartSpan(ctx, "cache.Get") +defer span.End() + +// Do work to get from cache. +``` + +### Propagation + +Spans can have parents or can be root spans if they don't have any parents. +The current span is propagated in-process and across the network to allow associating +new child spans with the parent. + +In the same process, `context.Context` is used to propagate spans. +`trace.StartSpan` creates a new span as a root if the current context +doesn't contain a span. Or, it creates a child of the span that is +already in current context. The returned context can be used to keep +propagating the newly created span in the current context. + +[embedmd]:# (internal/readme/trace.go startend) +```go +ctx, span := trace.StartSpan(ctx, "cache.Get") +defer span.End() + +// Do work to get from cache. +``` + +Across the network, OpenCensus provides different propagation +methods for different protocols. + +* gRPC integrations use the OpenCensus' [binary propagation format](https://godoc.org/go.opencensus.io/trace/propagation). +* HTTP integrations use Zipkin's [B3](https://github.com/openzipkin/b3-propagation) + by default but can be configured to use a custom propagation method by setting another + [propagation.HTTPFormat](https://godoc.org/go.opencensus.io/trace/propagation#HTTPFormat). + +## Execution Tracer + +With Go 1.11, OpenCensus Go will support integration with the Go execution tracer. +See [Debugging Latency in Go](https://medium.com/observability/debugging-latency-in-go-1-11-9f97a7910d68) +for an example of their mutual use. + +## Profiles + +OpenCensus tags can be applied as profiler labels +for users who are on Go 1.9 and above. + +[embedmd]:# (internal/readme/tags.go profiler) +```go +ctx, err = tag.New(ctx, + tag.Insert(osKey, "macOS-10.12.5"), + tag.Insert(userIDKey, "fff0989878"), +) +if err != nil { + log.Fatal(err) +} +tag.Do(ctx, func(ctx context.Context) { + // Do work. + // When profiling is on, samples will be + // recorded with the key/values from the tag map. +}) +``` + +A screenshot of the CPU profile from the program above: + +![CPU profile](https://i.imgur.com/jBKjlkw.png) + +## Deprecation Policy + +Before version 1.0.0, the following deprecation policy will be observed: + +No backwards-incompatible changes will be made except for the removal of symbols that have +been marked as *Deprecated* for at least one minor release (e.g. 0.9.0 to 0.10.0). A release +removing the *Deprecated* functionality will be made no sooner than 28 days after the first +release in which the functionality was marked *Deprecated*. + +[travis-image]: https://travis-ci.org/census-instrumentation/opencensus-go.svg?branch=master +[travis-url]: https://travis-ci.org/census-instrumentation/opencensus-go +[appveyor-image]: https://ci.appveyor.com/api/projects/status/vgtt29ps1783ig38?svg=true +[appveyor-url]: https://ci.appveyor.com/project/opencensusgoteam/opencensus-go/branch/master +[godoc-image]: https://godoc.org/go.opencensus.io?status.svg +[godoc-url]: https://godoc.org/go.opencensus.io +[gitter-image]: https://badges.gitter.im/census-instrumentation/lobby.svg +[gitter-url]: https://gitter.im/census-instrumentation/lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge + + +[new-ex]: https://godoc.org/go.opencensus.io/tag#example-NewMap +[new-replace-ex]: https://godoc.org/go.opencensus.io/tag#example-NewMap--Replace + +[exporter-prom]: https://godoc.org/go.opencensus.io/exporter/prometheus +[exporter-stackdriver]: https://godoc.org/contrib.go.opencensus.io/exporter/stackdriver +[exporter-zipkin]: https://godoc.org/go.opencensus.io/exporter/zipkin +[exporter-jaeger]: https://godoc.org/go.opencensus.io/exporter/jaeger +[exporter-xray]: https://github.com/census-ecosystem/opencensus-go-exporter-aws +[exporter-datadog]: https://github.com/DataDog/opencensus-go-exporter-datadog +[exporter-graphite]: https://github.com/census-ecosystem/opencensus-go-exporter-graphite +[exporter-honeycomb]: https://github.com/honeycombio/opencensus-exporter diff --git a/vendor/go.opencensus.io/appveyor.yml b/vendor/go.opencensus.io/appveyor.yml new file mode 100644 index 00000000..12bd7c4c --- /dev/null +++ b/vendor/go.opencensus.io/appveyor.yml @@ -0,0 +1,25 @@ +version: "{build}" + +platform: x64 + +clone_folder: c:\gopath\src\go.opencensus.io + +environment: + GOPATH: 'c:\gopath' + GOVERSION: '1.11' + GO111MODULE: 'on' + CGO_ENABLED: '0' # See: https://github.com/appveyor/ci/issues/2613 + +install: + - set PATH=%GOPATH%\bin;c:\go\bin;%PATH% + - choco upgrade golang --version 1.11.5 # Temporary fix because of a go.sum bug in 1.11 + - go version + - go env + +build: false +deploy: false + +test_script: + - cd %APPVEYOR_BUILD_FOLDER% + - go build -v .\... + - go test -v .\... # No -race because cgo is disabled diff --git a/vendor/go.opencensus.io/go.mod b/vendor/go.opencensus.io/go.mod new file mode 100644 index 00000000..8b7d38e9 --- /dev/null +++ b/vendor/go.opencensus.io/go.mod @@ -0,0 +1,10 @@ +module go.opencensus.io + +require ( + github.com/golang/protobuf v1.2.0 + github.com/google/go-cmp v0.2.0 + github.com/hashicorp/golang-lru v0.5.0 + golang.org/x/net v0.0.0-20190311183353-d8887717615a + google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19 // indirect + google.golang.org/grpc v1.19.0 +) diff --git a/vendor/go.opencensus.io/go.sum b/vendor/go.opencensus.io/go.sum new file mode 100644 index 00000000..cbb37036 --- /dev/null +++ b/vendor/go.opencensus.io/go.sum @@ -0,0 +1,50 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/hashicorp/golang-lru v0.5.0 h1:CL2msUPvZTLb5O648aiLNJw3hnBxN2+1Jq8rCOH9wdo= +github.com/hashicorp/golang-lru v0.5.0 h1:CL2msUPvZTLb5O648aiLNJw3hnBxN2+1Jq8rCOH9wdo= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f h1:Bl/8QSvNqXvPGPGXa2z5xUTmV7VDcZyvRZ+QQXkXTZQ= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6 h1:bjcUS9ztw9kFmmIxJInhon/0Is3p+EHBKNgquIzo1OI= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19 h1:Lj2SnHtxkRGJDqnGaSjo+CCdIieEnwVazbOXILwQemk= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/grpc v1.19.0 h1:cfg4PD8YEdSFnm7qLV4++93WcmhH2nIUhMjhdCvl3j8= +google.golang.org/grpc v1.19.0 h1:cfg4PD8YEdSFnm7qLV4++93WcmhH2nIUhMjhdCvl3j8= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/vendor/go.opencensus.io/internal/internal.go b/vendor/go.opencensus.io/internal/internal.go new file mode 100644 index 00000000..9a638781 --- /dev/null +++ b/vendor/go.opencensus.io/internal/internal.go @@ -0,0 +1,37 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package internal // import "go.opencensus.io/internal" + +import ( + "fmt" + "time" + + opencensus "go.opencensus.io" +) + +// UserAgent is the user agent to be added to the outgoing +// requests from the exporters. +var UserAgent = fmt.Sprintf("opencensus-go/%s", opencensus.Version()) + +// MonotonicEndTime returns the end time at present +// but offset from start, monotonically. +// +// The monotonic clock is used in subtractions hence +// the duration since start added back to start gives +// end as a monotonic time. +// See https://golang.org/pkg/time/#hdr-Monotonic_Clocks +func MonotonicEndTime(start time.Time) time.Time { + return start.Add(time.Now().Sub(start)) +} diff --git a/vendor/go.opencensus.io/internal/sanitize.go b/vendor/go.opencensus.io/internal/sanitize.go new file mode 100644 index 00000000..de8ccf23 --- /dev/null +++ b/vendor/go.opencensus.io/internal/sanitize.go @@ -0,0 +1,50 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package internal + +import ( + "strings" + "unicode" +) + +const labelKeySizeLimit = 100 + +// Sanitize returns a string that is trunacated to 100 characters if it's too +// long, and replaces non-alphanumeric characters to underscores. +func Sanitize(s string) string { + if len(s) == 0 { + return s + } + if len(s) > labelKeySizeLimit { + s = s[:labelKeySizeLimit] + } + s = strings.Map(sanitizeRune, s) + if unicode.IsDigit(rune(s[0])) { + s = "key_" + s + } + if s[0] == '_' { + s = "key" + s + } + return s +} + +// converts anything that is not a letter or digit to an underscore +func sanitizeRune(r rune) rune { + if unicode.IsLetter(r) || unicode.IsDigit(r) { + return r + } + // Everything else turns into an underscore + return '_' +} diff --git a/vendor/go.opencensus.io/internal/tagencoding/tagencoding.go b/vendor/go.opencensus.io/internal/tagencoding/tagencoding.go new file mode 100644 index 00000000..41b2c3fc --- /dev/null +++ b/vendor/go.opencensus.io/internal/tagencoding/tagencoding.go @@ -0,0 +1,75 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// Package tagencoding contains the tag encoding +// used interally by the stats collector. +package tagencoding // import "go.opencensus.io/internal/tagencoding" + +// Values represent the encoded buffer for the values. +type Values struct { + Buffer []byte + WriteIndex int + ReadIndex int +} + +func (vb *Values) growIfRequired(expected int) { + if len(vb.Buffer)-vb.WriteIndex < expected { + tmp := make([]byte, 2*(len(vb.Buffer)+1)+expected) + copy(tmp, vb.Buffer) + vb.Buffer = tmp + } +} + +// WriteValue is the helper method to encode Values from map[Key][]byte. +func (vb *Values) WriteValue(v []byte) { + length := len(v) & 0xff + vb.growIfRequired(1 + length) + + // writing length of v + vb.Buffer[vb.WriteIndex] = byte(length) + vb.WriteIndex++ + + if length == 0 { + // No value was encoded for this key + return + } + + // writing v + copy(vb.Buffer[vb.WriteIndex:], v[:length]) + vb.WriteIndex += length +} + +// ReadValue is the helper method to decode Values to a map[Key][]byte. +func (vb *Values) ReadValue() []byte { + // read length of v + length := int(vb.Buffer[vb.ReadIndex]) + vb.ReadIndex++ + if length == 0 { + // No value was encoded for this key + return nil + } + + // read value of v + v := make([]byte, length) + endIdx := vb.ReadIndex + length + copy(v, vb.Buffer[vb.ReadIndex:endIdx]) + vb.ReadIndex = endIdx + return v +} + +// Bytes returns a reference to already written bytes in the Buffer. +func (vb *Values) Bytes() []byte { + return vb.Buffer[:vb.WriteIndex] +} diff --git a/vendor/go.opencensus.io/internal/traceinternals.go b/vendor/go.opencensus.io/internal/traceinternals.go new file mode 100644 index 00000000..073af7b4 --- /dev/null +++ b/vendor/go.opencensus.io/internal/traceinternals.go @@ -0,0 +1,53 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package internal + +import ( + "time" +) + +// Trace allows internal access to some trace functionality. +// TODO(#412): remove this +var Trace interface{} + +// LocalSpanStoreEnabled true if the local span store is enabled. +var LocalSpanStoreEnabled bool + +// BucketConfiguration stores the number of samples to store for span buckets +// for successful and failed spans for a particular span name. +type BucketConfiguration struct { + Name string + MaxRequestsSucceeded int + MaxRequestsErrors int +} + +// PerMethodSummary is a summary of the spans stored for a single span name. +type PerMethodSummary struct { + Active int + LatencyBuckets []LatencyBucketSummary + ErrorBuckets []ErrorBucketSummary +} + +// LatencyBucketSummary is a summary of a latency bucket. +type LatencyBucketSummary struct { + MinLatency, MaxLatency time.Duration + Size int +} + +// ErrorBucketSummary is a summary of an error bucket. +type ErrorBucketSummary struct { + ErrorCode int32 + Size int +} diff --git a/vendor/go.opencensus.io/metric/metricdata/doc.go b/vendor/go.opencensus.io/metric/metricdata/doc.go new file mode 100644 index 00000000..52a7b3bf --- /dev/null +++ b/vendor/go.opencensus.io/metric/metricdata/doc.go @@ -0,0 +1,19 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package metricdata contains the metrics data model. +// +// This is an EXPERIMENTAL package, and may change in arbitrary ways without +// notice. +package metricdata // import "go.opencensus.io/metric/metricdata" diff --git a/vendor/go.opencensus.io/metric/metricdata/exemplar.go b/vendor/go.opencensus.io/metric/metricdata/exemplar.go new file mode 100644 index 00000000..12695ce2 --- /dev/null +++ b/vendor/go.opencensus.io/metric/metricdata/exemplar.go @@ -0,0 +1,38 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package metricdata + +import ( + "time" +) + +// Exemplars keys. +const ( + AttachmentKeySpanContext = "SpanContext" +) + +// Exemplar is an example data point associated with each bucket of a +// distribution type aggregation. +// +// Their purpose is to provide an example of the kind of thing +// (request, RPC, trace span, etc.) that resulted in that measurement. +type Exemplar struct { + Value float64 // the value that was recorded + Timestamp time.Time // the time the value was recorded + Attachments Attachments // attachments (if any) +} + +// Attachments is a map of extra values associated with a recorded data point. +type Attachments map[string]interface{} diff --git a/vendor/go.opencensus.io/metric/metricdata/label.go b/vendor/go.opencensus.io/metric/metricdata/label.go new file mode 100644 index 00000000..aadae41e --- /dev/null +++ b/vendor/go.opencensus.io/metric/metricdata/label.go @@ -0,0 +1,35 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package metricdata + +// LabelKey represents key of a label. It has optional +// description attribute. +type LabelKey struct { + Key string + Description string +} + +// LabelValue represents the value of a label. +// The zero value represents a missing label value, which may be treated +// differently to an empty string value by some back ends. +type LabelValue struct { + Value string // string value of the label + Present bool // flag that indicated whether a value is present or not +} + +// NewLabelValue creates a new non-nil LabelValue that represents the given string. +func NewLabelValue(val string) LabelValue { + return LabelValue{Value: val, Present: true} +} diff --git a/vendor/go.opencensus.io/metric/metricdata/metric.go b/vendor/go.opencensus.io/metric/metricdata/metric.go new file mode 100644 index 00000000..8293712c --- /dev/null +++ b/vendor/go.opencensus.io/metric/metricdata/metric.go @@ -0,0 +1,46 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package metricdata + +import ( + "time" + + "go.opencensus.io/resource" +) + +// Descriptor holds metadata about a metric. +type Descriptor struct { + Name string // full name of the metric + Description string // human-readable description + Unit Unit // units for the measure + Type Type // type of measure + LabelKeys []LabelKey // label keys +} + +// Metric represents a quantity measured against a resource with different +// label value combinations. +type Metric struct { + Descriptor Descriptor // metric descriptor + Resource *resource.Resource // resource against which this was measured + TimeSeries []*TimeSeries // one time series for each combination of label values +} + +// TimeSeries is a sequence of points associated with a combination of label +// values. +type TimeSeries struct { + LabelValues []LabelValue // label values, same order as keys in the metric descriptor + Points []Point // points sequence + StartTime time.Time // time we started recording this time series +} diff --git a/vendor/go.opencensus.io/metric/metricdata/point.go b/vendor/go.opencensus.io/metric/metricdata/point.go new file mode 100644 index 00000000..7fe057b1 --- /dev/null +++ b/vendor/go.opencensus.io/metric/metricdata/point.go @@ -0,0 +1,193 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package metricdata + +import ( + "time" +) + +// Point is a single data point of a time series. +type Point struct { + // Time is the point in time that this point represents in a time series. + Time time.Time + // Value is the value of this point. Prefer using ReadValue to switching on + // the value type, since new value types might be added. + Value interface{} +} + +//go:generate stringer -type ValueType + +// NewFloat64Point creates a new Point holding a float64 value. +func NewFloat64Point(t time.Time, val float64) Point { + return Point{ + Value: val, + Time: t, + } +} + +// NewInt64Point creates a new Point holding an int64 value. +func NewInt64Point(t time.Time, val int64) Point { + return Point{ + Value: val, + Time: t, + } +} + +// NewDistributionPoint creates a new Point holding a Distribution value. +func NewDistributionPoint(t time.Time, val *Distribution) Point { + return Point{ + Value: val, + Time: t, + } +} + +// NewSummaryPoint creates a new Point holding a Summary value. +func NewSummaryPoint(t time.Time, val *Summary) Point { + return Point{ + Value: val, + Time: t, + } +} + +// ValueVisitor allows reading the value of a point. +type ValueVisitor interface { + VisitFloat64Value(float64) + VisitInt64Value(int64) + VisitDistributionValue(*Distribution) + VisitSummaryValue(*Summary) +} + +// ReadValue accepts a ValueVisitor and calls the appropriate method with the +// value of this point. +// Consumers of Point should use this in preference to switching on the type +// of the value directly, since new value types may be added. +func (p Point) ReadValue(vv ValueVisitor) { + switch v := p.Value.(type) { + case int64: + vv.VisitInt64Value(v) + case float64: + vv.VisitFloat64Value(v) + case *Distribution: + vv.VisitDistributionValue(v) + case *Summary: + vv.VisitSummaryValue(v) + default: + panic("unexpected value type") + } +} + +// Distribution contains summary statistics for a population of values. It +// optionally contains a histogram representing the distribution of those +// values across a set of buckets. +type Distribution struct { + // Count is the number of values in the population. Must be non-negative. This value + // must equal the sum of the values in bucket_counts if a histogram is + // provided. + Count int64 + // Sum is the sum of the values in the population. If count is zero then this field + // must be zero. + Sum float64 + // SumOfSquaredDeviation is the sum of squared deviations from the mean of the values in the + // population. For values x_i this is: + // + // Sum[i=1..n]((x_i - mean)^2) + // + // Knuth, "The Art of Computer Programming", Vol. 2, page 323, 3rd edition + // describes Welford's method for accumulating this sum in one pass. + // + // If count is zero then this field must be zero. + SumOfSquaredDeviation float64 + // BucketOptions describes the bounds of the histogram buckets in this + // distribution. + // + // A Distribution may optionally contain a histogram of the values in the + // population. + // + // If nil, there is no associated histogram. + BucketOptions *BucketOptions + // Bucket If the distribution does not have a histogram, then omit this field. + // If there is a histogram, then the sum of the values in the Bucket counts + // must equal the value in the count field of the distribution. + Buckets []Bucket +} + +// BucketOptions describes the bounds of the histogram buckets in this +// distribution. +type BucketOptions struct { + // Bounds specifies a set of bucket upper bounds. + // This defines len(bounds) + 1 (= N) buckets. The boundaries for bucket + // index i are: + // + // [0, Bounds[i]) for i == 0 + // [Bounds[i-1], Bounds[i]) for 0 < i < N-1 + // [Bounds[i-1], +infinity) for i == N-1 + Bounds []float64 +} + +// Bucket represents a single bucket (value range) in a distribution. +type Bucket struct { + // Count is the number of values in each bucket of the histogram, as described in + // bucket_bounds. + Count int64 + // Exemplar associated with this bucket (if any). + Exemplar *Exemplar +} + +// Summary is a representation of percentiles. +type Summary struct { + // Count is the cumulative count (if available). + Count int64 + // Sum is the cumulative sum of values (if available). + Sum float64 + // HasCountAndSum is true if Count and Sum are available. + HasCountAndSum bool + // Snapshot represents percentiles calculated over an arbitrary time window. + // The values in this struct can be reset at arbitrary unknown times, with + // the requirement that all of them are reset at the same time. + Snapshot Snapshot +} + +// Snapshot represents percentiles over an arbitrary time. +// The values in this struct can be reset at arbitrary unknown times, with +// the requirement that all of them are reset at the same time. +type Snapshot struct { + // Count is the number of values in the snapshot. Optional since some systems don't + // expose this. Set to 0 if not available. + Count int64 + // Sum is the sum of values in the snapshot. Optional since some systems don't + // expose this. If count is 0 then this field must be zero. + Sum float64 + // Percentiles is a map from percentile (range (0-100.0]) to the value of + // the percentile. + Percentiles map[float64]float64 +} + +//go:generate stringer -type Type + +// Type is the overall type of metric, including its value type and whether it +// represents a cumulative total (since the start time) or if it represents a +// gauge value. +type Type int + +// Metric types. +const ( + TypeGaugeInt64 Type = iota + TypeGaugeFloat64 + TypeGaugeDistribution + TypeCumulativeInt64 + TypeCumulativeFloat64 + TypeCumulativeDistribution + TypeSummary +) diff --git a/vendor/go.opencensus.io/metric/metricdata/type_string.go b/vendor/go.opencensus.io/metric/metricdata/type_string.go new file mode 100644 index 00000000..c3f8ec27 --- /dev/null +++ b/vendor/go.opencensus.io/metric/metricdata/type_string.go @@ -0,0 +1,16 @@ +// Code generated by "stringer -type Type"; DO NOT EDIT. + +package metricdata + +import "strconv" + +const _Type_name = "TypeGaugeInt64TypeGaugeFloat64TypeGaugeDistributionTypeCumulativeInt64TypeCumulativeFloat64TypeCumulativeDistributionTypeSummary" + +var _Type_index = [...]uint8{0, 14, 30, 51, 70, 91, 117, 128} + +func (i Type) String() string { + if i < 0 || i >= Type(len(_Type_index)-1) { + return "Type(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _Type_name[_Type_index[i]:_Type_index[i+1]] +} diff --git a/vendor/go.opencensus.io/metric/metricdata/unit.go b/vendor/go.opencensus.io/metric/metricdata/unit.go new file mode 100644 index 00000000..b483a137 --- /dev/null +++ b/vendor/go.opencensus.io/metric/metricdata/unit.go @@ -0,0 +1,27 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package metricdata + +// Unit is a string encoded according to the case-sensitive abbreviations from the +// Unified Code for Units of Measure: http://unitsofmeasure.org/ucum.html +type Unit string + +// Predefined units. To record against a unit not represented here, create your +// own Unit type constant from a string. +const ( + UnitDimensionless Unit = "1" + UnitBytes Unit = "By" + UnitMilliseconds Unit = "ms" +) diff --git a/vendor/go.opencensus.io/metric/metricproducer/manager.go b/vendor/go.opencensus.io/metric/metricproducer/manager.go new file mode 100644 index 00000000..ca1f3904 --- /dev/null +++ b/vendor/go.opencensus.io/metric/metricproducer/manager.go @@ -0,0 +1,78 @@ +// Copyright 2019, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package metricproducer + +import ( + "sync" +) + +// Manager maintains a list of active producers. Producers can register +// with the manager to allow readers to read all metrics provided by them. +// Readers can retrieve all producers registered with the manager, +// read metrics from the producers and export them. +type Manager struct { + mu sync.RWMutex + producers map[Producer]struct{} +} + +var prodMgr *Manager +var once sync.Once + +// GlobalManager is a single instance of producer manager +// that is used by all producers and all readers. +func GlobalManager() *Manager { + once.Do(func() { + prodMgr = &Manager{} + prodMgr.producers = make(map[Producer]struct{}) + }) + return prodMgr +} + +// AddProducer adds the producer to the Manager if it is not already present. +func (pm *Manager) AddProducer(producer Producer) { + if producer == nil { + return + } + pm.mu.Lock() + defer pm.mu.Unlock() + pm.producers[producer] = struct{}{} +} + +// DeleteProducer deletes the producer from the Manager if it is present. +func (pm *Manager) DeleteProducer(producer Producer) { + if producer == nil { + return + } + pm.mu.Lock() + defer pm.mu.Unlock() + delete(pm.producers, producer) +} + +// GetAll returns a slice of all producer currently registered with +// the Manager. For each call it generates a new slice. The slice +// should not be cached as registration may change at any time. It is +// typically called periodically by exporter to read metrics from +// the producers. +func (pm *Manager) GetAll() []Producer { + pm.mu.Lock() + defer pm.mu.Unlock() + producers := make([]Producer, len(pm.producers)) + i := 0 + for producer := range pm.producers { + producers[i] = producer + i++ + } + return producers +} diff --git a/vendor/go.opencensus.io/metric/metricproducer/producer.go b/vendor/go.opencensus.io/metric/metricproducer/producer.go new file mode 100644 index 00000000..6cee9ed1 --- /dev/null +++ b/vendor/go.opencensus.io/metric/metricproducer/producer.go @@ -0,0 +1,28 @@ +// Copyright 2019, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package metricproducer + +import ( + "go.opencensus.io/metric/metricdata" +) + +// Producer is a source of metrics. +type Producer interface { + // Read should return the current values of all metrics supported by this + // metric provider. + // The returned metrics should be unique for each combination of name and + // resource. + Read() []*metricdata.Metric +} diff --git a/vendor/go.opencensus.io/opencensus.go b/vendor/go.opencensus.io/opencensus.go new file mode 100644 index 00000000..d2565f1e --- /dev/null +++ b/vendor/go.opencensus.io/opencensus.go @@ -0,0 +1,21 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package opencensus contains Go support for OpenCensus. +package opencensus // import "go.opencensus.io" + +// Version is the current release version of OpenCensus in use. +func Version() string { + return "0.21.0" +} diff --git a/vendor/go.opencensus.io/plugin/ochttp/client.go b/vendor/go.opencensus.io/plugin/ochttp/client.go new file mode 100644 index 00000000..da815b2a --- /dev/null +++ b/vendor/go.opencensus.io/plugin/ochttp/client.go @@ -0,0 +1,117 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package ochttp + +import ( + "net/http" + "net/http/httptrace" + + "go.opencensus.io/trace" + "go.opencensus.io/trace/propagation" +) + +// Transport is an http.RoundTripper that instruments all outgoing requests with +// OpenCensus stats and tracing. +// +// The zero value is intended to be a useful default, but for +// now it's recommended that you explicitly set Propagation, since the default +// for this may change. +type Transport struct { + // Base may be set to wrap another http.RoundTripper that does the actual + // requests. By default http.DefaultTransport is used. + // + // If base HTTP roundtripper implements CancelRequest, + // the returned round tripper will be cancelable. + Base http.RoundTripper + + // Propagation defines how traces are propagated. If unspecified, a default + // (currently B3 format) will be used. + Propagation propagation.HTTPFormat + + // StartOptions are applied to the span started by this Transport around each + // request. + // + // StartOptions.SpanKind will always be set to trace.SpanKindClient + // for spans started by this transport. + StartOptions trace.StartOptions + + // GetStartOptions allows to set start options per request. If set, + // StartOptions is going to be ignored. + GetStartOptions func(*http.Request) trace.StartOptions + + // NameFromRequest holds the function to use for generating the span name + // from the information found in the outgoing HTTP Request. By default the + // name equals the URL Path. + FormatSpanName func(*http.Request) string + + // NewClientTrace may be set to a function allowing the current *trace.Span + // to be annotated with HTTP request event information emitted by the + // httptrace package. + NewClientTrace func(*http.Request, *trace.Span) *httptrace.ClientTrace + + // TODO: Implement tag propagation for HTTP. +} + +// RoundTrip implements http.RoundTripper, delegating to Base and recording stats and traces for the request. +func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { + rt := t.base() + if isHealthEndpoint(req.URL.Path) { + return rt.RoundTrip(req) + } + // TODO: remove excessive nesting of http.RoundTrippers here. + format := t.Propagation + if format == nil { + format = defaultFormat + } + spanNameFormatter := t.FormatSpanName + if spanNameFormatter == nil { + spanNameFormatter = spanNameFromURL + } + + startOpts := t.StartOptions + if t.GetStartOptions != nil { + startOpts = t.GetStartOptions(req) + } + + rt = &traceTransport{ + base: rt, + format: format, + startOptions: trace.StartOptions{ + Sampler: startOpts.Sampler, + SpanKind: trace.SpanKindClient, + }, + formatSpanName: spanNameFormatter, + newClientTrace: t.NewClientTrace, + } + rt = statsTransport{base: rt} + return rt.RoundTrip(req) +} + +func (t *Transport) base() http.RoundTripper { + if t.Base != nil { + return t.Base + } + return http.DefaultTransport +} + +// CancelRequest cancels an in-flight request by closing its connection. +func (t *Transport) CancelRequest(req *http.Request) { + type canceler interface { + CancelRequest(*http.Request) + } + if cr, ok := t.base().(canceler); ok { + cr.CancelRequest(req) + } +} diff --git a/vendor/go.opencensus.io/plugin/ochttp/client_stats.go b/vendor/go.opencensus.io/plugin/ochttp/client_stats.go new file mode 100644 index 00000000..17142aab --- /dev/null +++ b/vendor/go.opencensus.io/plugin/ochttp/client_stats.go @@ -0,0 +1,143 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package ochttp + +import ( + "context" + "io" + "net/http" + "strconv" + "sync" + "time" + + "go.opencensus.io/stats" + "go.opencensus.io/tag" +) + +// statsTransport is an http.RoundTripper that collects stats for the outgoing requests. +type statsTransport struct { + base http.RoundTripper +} + +// RoundTrip implements http.RoundTripper, delegating to Base and recording stats for the request. +func (t statsTransport) RoundTrip(req *http.Request) (*http.Response, error) { + ctx, _ := tag.New(req.Context(), + tag.Upsert(KeyClientHost, req.Host), + tag.Upsert(Host, req.Host), + tag.Upsert(KeyClientPath, req.URL.Path), + tag.Upsert(Path, req.URL.Path), + tag.Upsert(KeyClientMethod, req.Method), + tag.Upsert(Method, req.Method)) + req = req.WithContext(ctx) + track := &tracker{ + start: time.Now(), + ctx: ctx, + } + if req.Body == nil { + // TODO: Handle cases where ContentLength is not set. + track.reqSize = -1 + } else if req.ContentLength > 0 { + track.reqSize = req.ContentLength + } + stats.Record(ctx, ClientRequestCount.M(1)) + + // Perform request. + resp, err := t.base.RoundTrip(req) + + if err != nil { + track.statusCode = http.StatusInternalServerError + track.end() + } else { + track.statusCode = resp.StatusCode + if req.Method != "HEAD" { + track.respContentLength = resp.ContentLength + } + if resp.Body == nil { + track.end() + } else { + track.body = resp.Body + resp.Body = wrappedBody(track, resp.Body) + } + } + return resp, err +} + +// CancelRequest cancels an in-flight request by closing its connection. +func (t statsTransport) CancelRequest(req *http.Request) { + type canceler interface { + CancelRequest(*http.Request) + } + if cr, ok := t.base.(canceler); ok { + cr.CancelRequest(req) + } +} + +type tracker struct { + ctx context.Context + respSize int64 + respContentLength int64 + reqSize int64 + start time.Time + body io.ReadCloser + statusCode int + endOnce sync.Once +} + +var _ io.ReadCloser = (*tracker)(nil) + +func (t *tracker) end() { + t.endOnce.Do(func() { + latencyMs := float64(time.Since(t.start)) / float64(time.Millisecond) + respSize := t.respSize + if t.respSize == 0 && t.respContentLength > 0 { + respSize = t.respContentLength + } + m := []stats.Measurement{ + ClientSentBytes.M(t.reqSize), + ClientReceivedBytes.M(respSize), + ClientRoundtripLatency.M(latencyMs), + ClientLatency.M(latencyMs), + ClientResponseBytes.M(t.respSize), + } + if t.reqSize >= 0 { + m = append(m, ClientRequestBytes.M(t.reqSize)) + } + + stats.RecordWithTags(t.ctx, []tag.Mutator{ + tag.Upsert(StatusCode, strconv.Itoa(t.statusCode)), + tag.Upsert(KeyClientStatus, strconv.Itoa(t.statusCode)), + }, m...) + }) +} + +func (t *tracker) Read(b []byte) (int, error) { + n, err := t.body.Read(b) + t.respSize += int64(n) + switch err { + case nil: + return n, nil + case io.EOF: + t.end() + } + return n, err +} + +func (t *tracker) Close() error { + // Invoking endSpan on Close will help catch the cases + // in which a read returned a non-nil error, we set the + // span status but didn't end the span. + t.end() + return t.body.Close() +} diff --git a/vendor/go.opencensus.io/plugin/ochttp/doc.go b/vendor/go.opencensus.io/plugin/ochttp/doc.go new file mode 100644 index 00000000..10e626b1 --- /dev/null +++ b/vendor/go.opencensus.io/plugin/ochttp/doc.go @@ -0,0 +1,19 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package ochttp provides OpenCensus instrumentation for net/http package. +// +// For server instrumentation, see Handler. For client-side instrumentation, +// see Transport. +package ochttp // import "go.opencensus.io/plugin/ochttp" diff --git a/vendor/go.opencensus.io/plugin/ochttp/propagation/b3/b3.go b/vendor/go.opencensus.io/plugin/ochttp/propagation/b3/b3.go new file mode 100644 index 00000000..2f1c7f00 --- /dev/null +++ b/vendor/go.opencensus.io/plugin/ochttp/propagation/b3/b3.go @@ -0,0 +1,123 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package b3 contains a propagation.HTTPFormat implementation +// for B3 propagation. See https://github.com/openzipkin/b3-propagation +// for more details. +package b3 // import "go.opencensus.io/plugin/ochttp/propagation/b3" + +import ( + "encoding/hex" + "net/http" + + "go.opencensus.io/trace" + "go.opencensus.io/trace/propagation" +) + +// B3 headers that OpenCensus understands. +const ( + TraceIDHeader = "X-B3-TraceId" + SpanIDHeader = "X-B3-SpanId" + SampledHeader = "X-B3-Sampled" +) + +// HTTPFormat implements propagation.HTTPFormat to propagate +// traces in HTTP headers in B3 propagation format. +// HTTPFormat skips the X-B3-ParentId and X-B3-Flags headers +// because there are additional fields not represented in the +// OpenCensus span context. Spans created from the incoming +// header will be the direct children of the client-side span. +// Similarly, receiver of the outgoing spans should use client-side +// span created by OpenCensus as the parent. +type HTTPFormat struct{} + +var _ propagation.HTTPFormat = (*HTTPFormat)(nil) + +// SpanContextFromRequest extracts a B3 span context from incoming requests. +func (f *HTTPFormat) SpanContextFromRequest(req *http.Request) (sc trace.SpanContext, ok bool) { + tid, ok := ParseTraceID(req.Header.Get(TraceIDHeader)) + if !ok { + return trace.SpanContext{}, false + } + sid, ok := ParseSpanID(req.Header.Get(SpanIDHeader)) + if !ok { + return trace.SpanContext{}, false + } + sampled, _ := ParseSampled(req.Header.Get(SampledHeader)) + return trace.SpanContext{ + TraceID: tid, + SpanID: sid, + TraceOptions: sampled, + }, true +} + +// ParseTraceID parses the value of the X-B3-TraceId header. +func ParseTraceID(tid string) (trace.TraceID, bool) { + if tid == "" { + return trace.TraceID{}, false + } + b, err := hex.DecodeString(tid) + if err != nil { + return trace.TraceID{}, false + } + var traceID trace.TraceID + if len(b) <= 8 { + // The lower 64-bits. + start := 8 + (8 - len(b)) + copy(traceID[start:], b) + } else { + start := 16 - len(b) + copy(traceID[start:], b) + } + + return traceID, true +} + +// ParseSpanID parses the value of the X-B3-SpanId or X-B3-ParentSpanId headers. +func ParseSpanID(sid string) (spanID trace.SpanID, ok bool) { + if sid == "" { + return trace.SpanID{}, false + } + b, err := hex.DecodeString(sid) + if err != nil { + return trace.SpanID{}, false + } + start := 8 - len(b) + copy(spanID[start:], b) + return spanID, true +} + +// ParseSampled parses the value of the X-B3-Sampled header. +func ParseSampled(sampled string) (trace.TraceOptions, bool) { + switch sampled { + case "true", "1": + return trace.TraceOptions(1), true + default: + return trace.TraceOptions(0), false + } +} + +// SpanContextToRequest modifies the given request to include B3 headers. +func (f *HTTPFormat) SpanContextToRequest(sc trace.SpanContext, req *http.Request) { + req.Header.Set(TraceIDHeader, hex.EncodeToString(sc.TraceID[:])) + req.Header.Set(SpanIDHeader, hex.EncodeToString(sc.SpanID[:])) + + var sampled string + if sc.IsSampled() { + sampled = "1" + } else { + sampled = "0" + } + req.Header.Set(SampledHeader, sampled) +} diff --git a/vendor/go.opencensus.io/plugin/ochttp/route.go b/vendor/go.opencensus.io/plugin/ochttp/route.go new file mode 100644 index 00000000..5e6a3430 --- /dev/null +++ b/vendor/go.opencensus.io/plugin/ochttp/route.go @@ -0,0 +1,61 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package ochttp + +import ( + "context" + "net/http" + + "go.opencensus.io/tag" +) + +// SetRoute sets the http_server_route tag to the given value. +// It's useful when an HTTP framework does not support the http.Handler interface +// and using WithRouteTag is not an option, but provides a way to hook into the request flow. +func SetRoute(ctx context.Context, route string) { + if a, ok := ctx.Value(addedTagsKey{}).(*addedTags); ok { + a.t = append(a.t, tag.Upsert(KeyServerRoute, route)) + } +} + +// WithRouteTag returns an http.Handler that records stats with the +// http_server_route tag set to the given value. +func WithRouteTag(handler http.Handler, route string) http.Handler { + return taggedHandlerFunc(func(w http.ResponseWriter, r *http.Request) []tag.Mutator { + addRoute := []tag.Mutator{tag.Upsert(KeyServerRoute, route)} + ctx, _ := tag.New(r.Context(), addRoute...) + r = r.WithContext(ctx) + handler.ServeHTTP(w, r) + return addRoute + }) +} + +// taggedHandlerFunc is a http.Handler that returns tags describing the +// processing of the request. These tags will be recorded along with the +// measures in this package at the end of the request. +type taggedHandlerFunc func(w http.ResponseWriter, r *http.Request) []tag.Mutator + +func (h taggedHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) { + tags := h(w, r) + if a, ok := r.Context().Value(addedTagsKey{}).(*addedTags); ok { + a.t = append(a.t, tags...) + } +} + +type addedTagsKey struct{} + +type addedTags struct { + t []tag.Mutator +} diff --git a/vendor/go.opencensus.io/plugin/ochttp/server.go b/vendor/go.opencensus.io/plugin/ochttp/server.go new file mode 100644 index 00000000..4f6404fa --- /dev/null +++ b/vendor/go.opencensus.io/plugin/ochttp/server.go @@ -0,0 +1,449 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package ochttp + +import ( + "context" + "io" + "net/http" + "strconv" + "sync" + "time" + + "go.opencensus.io/stats" + "go.opencensus.io/tag" + "go.opencensus.io/trace" + "go.opencensus.io/trace/propagation" +) + +// Handler is an http.Handler wrapper to instrument your HTTP server with +// OpenCensus. It supports both stats and tracing. +// +// Tracing +// +// This handler is aware of the incoming request's span, reading it from request +// headers as configured using the Propagation field. +// The extracted span can be accessed from the incoming request's +// context. +// +// span := trace.FromContext(r.Context()) +// +// The server span will be automatically ended at the end of ServeHTTP. +type Handler struct { + // Propagation defines how traces are propagated. If unspecified, + // B3 propagation will be used. + Propagation propagation.HTTPFormat + + // Handler is the handler used to handle the incoming request. + Handler http.Handler + + // StartOptions are applied to the span started by this Handler around each + // request. + // + // StartOptions.SpanKind will always be set to trace.SpanKindServer + // for spans started by this transport. + StartOptions trace.StartOptions + + // GetStartOptions allows to set start options per request. If set, + // StartOptions is going to be ignored. + GetStartOptions func(*http.Request) trace.StartOptions + + // IsPublicEndpoint should be set to true for publicly accessible HTTP(S) + // servers. If true, any trace metadata set on the incoming request will + // be added as a linked trace instead of being added as a parent of the + // current trace. + IsPublicEndpoint bool + + // FormatSpanName holds the function to use for generating the span name + // from the information found in the incoming HTTP Request. By default the + // name equals the URL Path. + FormatSpanName func(*http.Request) string +} + +func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + var tags addedTags + r, traceEnd := h.startTrace(w, r) + defer traceEnd() + w, statsEnd := h.startStats(w, r) + defer statsEnd(&tags) + handler := h.Handler + if handler == nil { + handler = http.DefaultServeMux + } + r = r.WithContext(context.WithValue(r.Context(), addedTagsKey{}, &tags)) + handler.ServeHTTP(w, r) +} + +func (h *Handler) startTrace(w http.ResponseWriter, r *http.Request) (*http.Request, func()) { + if isHealthEndpoint(r.URL.Path) { + return r, func() {} + } + var name string + if h.FormatSpanName == nil { + name = spanNameFromURL(r) + } else { + name = h.FormatSpanName(r) + } + ctx := r.Context() + + startOpts := h.StartOptions + if h.GetStartOptions != nil { + startOpts = h.GetStartOptions(r) + } + + var span *trace.Span + sc, ok := h.extractSpanContext(r) + if ok && !h.IsPublicEndpoint { + ctx, span = trace.StartSpanWithRemoteParent(ctx, name, sc, + trace.WithSampler(startOpts.Sampler), + trace.WithSpanKind(trace.SpanKindServer)) + } else { + ctx, span = trace.StartSpan(ctx, name, + trace.WithSampler(startOpts.Sampler), + trace.WithSpanKind(trace.SpanKindServer), + ) + if ok { + span.AddLink(trace.Link{ + TraceID: sc.TraceID, + SpanID: sc.SpanID, + Type: trace.LinkTypeParent, + Attributes: nil, + }) + } + } + span.AddAttributes(requestAttrs(r)...) + if r.Body == nil { + // TODO: Handle cases where ContentLength is not set. + } else if r.ContentLength > 0 { + span.AddMessageReceiveEvent(0, /* TODO: messageID */ + int64(r.ContentLength), -1) + } + return r.WithContext(ctx), span.End +} + +func (h *Handler) extractSpanContext(r *http.Request) (trace.SpanContext, bool) { + if h.Propagation == nil { + return defaultFormat.SpanContextFromRequest(r) + } + return h.Propagation.SpanContextFromRequest(r) +} + +func (h *Handler) startStats(w http.ResponseWriter, r *http.Request) (http.ResponseWriter, func(tags *addedTags)) { + ctx, _ := tag.New(r.Context(), + tag.Upsert(Host, r.Host), + tag.Upsert(Path, r.URL.Path), + tag.Upsert(Method, r.Method)) + track := &trackingResponseWriter{ + start: time.Now(), + ctx: ctx, + writer: w, + } + if r.Body == nil { + // TODO: Handle cases where ContentLength is not set. + track.reqSize = -1 + } else if r.ContentLength > 0 { + track.reqSize = r.ContentLength + } + stats.Record(ctx, ServerRequestCount.M(1)) + return track.wrappedResponseWriter(), track.end +} + +type trackingResponseWriter struct { + ctx context.Context + reqSize int64 + respSize int64 + start time.Time + statusCode int + statusLine string + endOnce sync.Once + writer http.ResponseWriter +} + +// Compile time assertion for ResponseWriter interface +var _ http.ResponseWriter = (*trackingResponseWriter)(nil) + +var logTagsErrorOnce sync.Once + +func (t *trackingResponseWriter) end(tags *addedTags) { + t.endOnce.Do(func() { + if t.statusCode == 0 { + t.statusCode = 200 + } + + span := trace.FromContext(t.ctx) + span.SetStatus(TraceStatus(t.statusCode, t.statusLine)) + span.AddAttributes(trace.Int64Attribute(StatusCodeAttribute, int64(t.statusCode))) + + m := []stats.Measurement{ + ServerLatency.M(float64(time.Since(t.start)) / float64(time.Millisecond)), + ServerResponseBytes.M(t.respSize), + } + if t.reqSize >= 0 { + m = append(m, ServerRequestBytes.M(t.reqSize)) + } + allTags := make([]tag.Mutator, len(tags.t)+1) + allTags[0] = tag.Upsert(StatusCode, strconv.Itoa(t.statusCode)) + copy(allTags[1:], tags.t) + stats.RecordWithTags(t.ctx, allTags, m...) + }) +} + +func (t *trackingResponseWriter) Header() http.Header { + return t.writer.Header() +} + +func (t *trackingResponseWriter) Write(data []byte) (int, error) { + n, err := t.writer.Write(data) + t.respSize += int64(n) + // Add message event for request bytes sent. + span := trace.FromContext(t.ctx) + span.AddMessageSendEvent(0 /* TODO: messageID */, int64(n), -1) + return n, err +} + +func (t *trackingResponseWriter) WriteHeader(statusCode int) { + t.writer.WriteHeader(statusCode) + t.statusCode = statusCode + t.statusLine = http.StatusText(t.statusCode) +} + +// wrappedResponseWriter returns a wrapped version of the original +// ResponseWriter and only implements the same combination of additional +// interfaces as the original. +// This implementation is based on https://github.com/felixge/httpsnoop. +func (t *trackingResponseWriter) wrappedResponseWriter() http.ResponseWriter { + var ( + hj, i0 = t.writer.(http.Hijacker) + cn, i1 = t.writer.(http.CloseNotifier) + pu, i2 = t.writer.(http.Pusher) + fl, i3 = t.writer.(http.Flusher) + rf, i4 = t.writer.(io.ReaderFrom) + ) + + switch { + case !i0 && !i1 && !i2 && !i3 && !i4: + return struct { + http.ResponseWriter + }{t} + case !i0 && !i1 && !i2 && !i3 && i4: + return struct { + http.ResponseWriter + io.ReaderFrom + }{t, rf} + case !i0 && !i1 && !i2 && i3 && !i4: + return struct { + http.ResponseWriter + http.Flusher + }{t, fl} + case !i0 && !i1 && !i2 && i3 && i4: + return struct { + http.ResponseWriter + http.Flusher + io.ReaderFrom + }{t, fl, rf} + case !i0 && !i1 && i2 && !i3 && !i4: + return struct { + http.ResponseWriter + http.Pusher + }{t, pu} + case !i0 && !i1 && i2 && !i3 && i4: + return struct { + http.ResponseWriter + http.Pusher + io.ReaderFrom + }{t, pu, rf} + case !i0 && !i1 && i2 && i3 && !i4: + return struct { + http.ResponseWriter + http.Pusher + http.Flusher + }{t, pu, fl} + case !i0 && !i1 && i2 && i3 && i4: + return struct { + http.ResponseWriter + http.Pusher + http.Flusher + io.ReaderFrom + }{t, pu, fl, rf} + case !i0 && i1 && !i2 && !i3 && !i4: + return struct { + http.ResponseWriter + http.CloseNotifier + }{t, cn} + case !i0 && i1 && !i2 && !i3 && i4: + return struct { + http.ResponseWriter + http.CloseNotifier + io.ReaderFrom + }{t, cn, rf} + case !i0 && i1 && !i2 && i3 && !i4: + return struct { + http.ResponseWriter + http.CloseNotifier + http.Flusher + }{t, cn, fl} + case !i0 && i1 && !i2 && i3 && i4: + return struct { + http.ResponseWriter + http.CloseNotifier + http.Flusher + io.ReaderFrom + }{t, cn, fl, rf} + case !i0 && i1 && i2 && !i3 && !i4: + return struct { + http.ResponseWriter + http.CloseNotifier + http.Pusher + }{t, cn, pu} + case !i0 && i1 && i2 && !i3 && i4: + return struct { + http.ResponseWriter + http.CloseNotifier + http.Pusher + io.ReaderFrom + }{t, cn, pu, rf} + case !i0 && i1 && i2 && i3 && !i4: + return struct { + http.ResponseWriter + http.CloseNotifier + http.Pusher + http.Flusher + }{t, cn, pu, fl} + case !i0 && i1 && i2 && i3 && i4: + return struct { + http.ResponseWriter + http.CloseNotifier + http.Pusher + http.Flusher + io.ReaderFrom + }{t, cn, pu, fl, rf} + case i0 && !i1 && !i2 && !i3 && !i4: + return struct { + http.ResponseWriter + http.Hijacker + }{t, hj} + case i0 && !i1 && !i2 && !i3 && i4: + return struct { + http.ResponseWriter + http.Hijacker + io.ReaderFrom + }{t, hj, rf} + case i0 && !i1 && !i2 && i3 && !i4: + return struct { + http.ResponseWriter + http.Hijacker + http.Flusher + }{t, hj, fl} + case i0 && !i1 && !i2 && i3 && i4: + return struct { + http.ResponseWriter + http.Hijacker + http.Flusher + io.ReaderFrom + }{t, hj, fl, rf} + case i0 && !i1 && i2 && !i3 && !i4: + return struct { + http.ResponseWriter + http.Hijacker + http.Pusher + }{t, hj, pu} + case i0 && !i1 && i2 && !i3 && i4: + return struct { + http.ResponseWriter + http.Hijacker + http.Pusher + io.ReaderFrom + }{t, hj, pu, rf} + case i0 && !i1 && i2 && i3 && !i4: + return struct { + http.ResponseWriter + http.Hijacker + http.Pusher + http.Flusher + }{t, hj, pu, fl} + case i0 && !i1 && i2 && i3 && i4: + return struct { + http.ResponseWriter + http.Hijacker + http.Pusher + http.Flusher + io.ReaderFrom + }{t, hj, pu, fl, rf} + case i0 && i1 && !i2 && !i3 && !i4: + return struct { + http.ResponseWriter + http.Hijacker + http.CloseNotifier + }{t, hj, cn} + case i0 && i1 && !i2 && !i3 && i4: + return struct { + http.ResponseWriter + http.Hijacker + http.CloseNotifier + io.ReaderFrom + }{t, hj, cn, rf} + case i0 && i1 && !i2 && i3 && !i4: + return struct { + http.ResponseWriter + http.Hijacker + http.CloseNotifier + http.Flusher + }{t, hj, cn, fl} + case i0 && i1 && !i2 && i3 && i4: + return struct { + http.ResponseWriter + http.Hijacker + http.CloseNotifier + http.Flusher + io.ReaderFrom + }{t, hj, cn, fl, rf} + case i0 && i1 && i2 && !i3 && !i4: + return struct { + http.ResponseWriter + http.Hijacker + http.CloseNotifier + http.Pusher + }{t, hj, cn, pu} + case i0 && i1 && i2 && !i3 && i4: + return struct { + http.ResponseWriter + http.Hijacker + http.CloseNotifier + http.Pusher + io.ReaderFrom + }{t, hj, cn, pu, rf} + case i0 && i1 && i2 && i3 && !i4: + return struct { + http.ResponseWriter + http.Hijacker + http.CloseNotifier + http.Pusher + http.Flusher + }{t, hj, cn, pu, fl} + case i0 && i1 && i2 && i3 && i4: + return struct { + http.ResponseWriter + http.Hijacker + http.CloseNotifier + http.Pusher + http.Flusher + io.ReaderFrom + }{t, hj, cn, pu, fl, rf} + default: + return struct { + http.ResponseWriter + }{t} + } +} diff --git a/vendor/go.opencensus.io/plugin/ochttp/span_annotating_client_trace.go b/vendor/go.opencensus.io/plugin/ochttp/span_annotating_client_trace.go new file mode 100644 index 00000000..05c6c56c --- /dev/null +++ b/vendor/go.opencensus.io/plugin/ochttp/span_annotating_client_trace.go @@ -0,0 +1,169 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package ochttp + +import ( + "crypto/tls" + "net/http" + "net/http/httptrace" + "strings" + + "go.opencensus.io/trace" +) + +type spanAnnotator struct { + sp *trace.Span +} + +// TODO: Remove NewSpanAnnotator at the next release. + +// NewSpanAnnotator returns a httptrace.ClientTrace which annotates +// all emitted httptrace events on the provided Span. +// Deprecated: Use NewSpanAnnotatingClientTrace instead +func NewSpanAnnotator(r *http.Request, s *trace.Span) *httptrace.ClientTrace { + return NewSpanAnnotatingClientTrace(r, s) +} + +// NewSpanAnnotatingClientTrace returns a httptrace.ClientTrace which annotates +// all emitted httptrace events on the provided Span. +func NewSpanAnnotatingClientTrace(_ *http.Request, s *trace.Span) *httptrace.ClientTrace { + sa := spanAnnotator{sp: s} + + return &httptrace.ClientTrace{ + GetConn: sa.getConn, + GotConn: sa.gotConn, + PutIdleConn: sa.putIdleConn, + GotFirstResponseByte: sa.gotFirstResponseByte, + Got100Continue: sa.got100Continue, + DNSStart: sa.dnsStart, + DNSDone: sa.dnsDone, + ConnectStart: sa.connectStart, + ConnectDone: sa.connectDone, + TLSHandshakeStart: sa.tlsHandshakeStart, + TLSHandshakeDone: sa.tlsHandshakeDone, + WroteHeaders: sa.wroteHeaders, + Wait100Continue: sa.wait100Continue, + WroteRequest: sa.wroteRequest, + } +} + +func (s spanAnnotator) getConn(hostPort string) { + attrs := []trace.Attribute{ + trace.StringAttribute("httptrace.get_connection.host_port", hostPort), + } + s.sp.Annotate(attrs, "GetConn") +} + +func (s spanAnnotator) gotConn(info httptrace.GotConnInfo) { + attrs := []trace.Attribute{ + trace.BoolAttribute("httptrace.got_connection.reused", info.Reused), + trace.BoolAttribute("httptrace.got_connection.was_idle", info.WasIdle), + } + if info.WasIdle { + attrs = append(attrs, + trace.StringAttribute("httptrace.got_connection.idle_time", info.IdleTime.String())) + } + s.sp.Annotate(attrs, "GotConn") +} + +// PutIdleConn implements a httptrace.ClientTrace hook +func (s spanAnnotator) putIdleConn(err error) { + var attrs []trace.Attribute + if err != nil { + attrs = append(attrs, + trace.StringAttribute("httptrace.put_idle_connection.error", err.Error())) + } + s.sp.Annotate(attrs, "PutIdleConn") +} + +func (s spanAnnotator) gotFirstResponseByte() { + s.sp.Annotate(nil, "GotFirstResponseByte") +} + +func (s spanAnnotator) got100Continue() { + s.sp.Annotate(nil, "Got100Continue") +} + +func (s spanAnnotator) dnsStart(info httptrace.DNSStartInfo) { + attrs := []trace.Attribute{ + trace.StringAttribute("httptrace.dns_start.host", info.Host), + } + s.sp.Annotate(attrs, "DNSStart") +} + +func (s spanAnnotator) dnsDone(info httptrace.DNSDoneInfo) { + var addrs []string + for _, addr := range info.Addrs { + addrs = append(addrs, addr.String()) + } + attrs := []trace.Attribute{ + trace.StringAttribute("httptrace.dns_done.addrs", strings.Join(addrs, " , ")), + } + if info.Err != nil { + attrs = append(attrs, + trace.StringAttribute("httptrace.dns_done.error", info.Err.Error())) + } + s.sp.Annotate(attrs, "DNSDone") +} + +func (s spanAnnotator) connectStart(network, addr string) { + attrs := []trace.Attribute{ + trace.StringAttribute("httptrace.connect_start.network", network), + trace.StringAttribute("httptrace.connect_start.addr", addr), + } + s.sp.Annotate(attrs, "ConnectStart") +} + +func (s spanAnnotator) connectDone(network, addr string, err error) { + attrs := []trace.Attribute{ + trace.StringAttribute("httptrace.connect_done.network", network), + trace.StringAttribute("httptrace.connect_done.addr", addr), + } + if err != nil { + attrs = append(attrs, + trace.StringAttribute("httptrace.connect_done.error", err.Error())) + } + s.sp.Annotate(attrs, "ConnectDone") +} + +func (s spanAnnotator) tlsHandshakeStart() { + s.sp.Annotate(nil, "TLSHandshakeStart") +} + +func (s spanAnnotator) tlsHandshakeDone(_ tls.ConnectionState, err error) { + var attrs []trace.Attribute + if err != nil { + attrs = append(attrs, + trace.StringAttribute("httptrace.tls_handshake_done.error", err.Error())) + } + s.sp.Annotate(attrs, "TLSHandshakeDone") +} + +func (s spanAnnotator) wroteHeaders() { + s.sp.Annotate(nil, "WroteHeaders") +} + +func (s spanAnnotator) wait100Continue() { + s.sp.Annotate(nil, "Wait100Continue") +} + +func (s spanAnnotator) wroteRequest(info httptrace.WroteRequestInfo) { + var attrs []trace.Attribute + if info.Err != nil { + attrs = append(attrs, + trace.StringAttribute("httptrace.wrote_request.error", info.Err.Error())) + } + s.sp.Annotate(attrs, "WroteRequest") +} diff --git a/vendor/go.opencensus.io/plugin/ochttp/stats.go b/vendor/go.opencensus.io/plugin/ochttp/stats.go new file mode 100644 index 00000000..63bbcda5 --- /dev/null +++ b/vendor/go.opencensus.io/plugin/ochttp/stats.go @@ -0,0 +1,292 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package ochttp + +import ( + "go.opencensus.io/stats" + "go.opencensus.io/stats/view" + "go.opencensus.io/tag" +) + +// Deprecated: client HTTP measures. +var ( + // Deprecated: Use a Count aggregation over one of the other client measures to achieve the same effect. + ClientRequestCount = stats.Int64( + "opencensus.io/http/client/request_count", + "Number of HTTP requests started", + stats.UnitDimensionless) + // Deprecated: Use ClientSentBytes. + ClientRequestBytes = stats.Int64( + "opencensus.io/http/client/request_bytes", + "HTTP request body size if set as ContentLength (uncompressed)", + stats.UnitBytes) + // Deprecated: Use ClientReceivedBytes. + ClientResponseBytes = stats.Int64( + "opencensus.io/http/client/response_bytes", + "HTTP response body size (uncompressed)", + stats.UnitBytes) + // Deprecated: Use ClientRoundtripLatency. + ClientLatency = stats.Float64( + "opencensus.io/http/client/latency", + "End-to-end latency", + stats.UnitMilliseconds) +) + +// The following client HTTP measures are supported for use in custom views. +var ( + ClientSentBytes = stats.Int64( + "opencensus.io/http/client/sent_bytes", + "Total bytes sent in request body (not including headers)", + stats.UnitBytes, + ) + ClientReceivedBytes = stats.Int64( + "opencensus.io/http/client/received_bytes", + "Total bytes received in response bodies (not including headers but including error responses with bodies)", + stats.UnitBytes, + ) + ClientRoundtripLatency = stats.Float64( + "opencensus.io/http/client/roundtrip_latency", + "Time between first byte of request headers sent to last byte of response received, or terminal error", + stats.UnitMilliseconds, + ) +) + +// The following server HTTP measures are supported for use in custom views: +var ( + ServerRequestCount = stats.Int64( + "opencensus.io/http/server/request_count", + "Number of HTTP requests started", + stats.UnitDimensionless) + ServerRequestBytes = stats.Int64( + "opencensus.io/http/server/request_bytes", + "HTTP request body size if set as ContentLength (uncompressed)", + stats.UnitBytes) + ServerResponseBytes = stats.Int64( + "opencensus.io/http/server/response_bytes", + "HTTP response body size (uncompressed)", + stats.UnitBytes) + ServerLatency = stats.Float64( + "opencensus.io/http/server/latency", + "End-to-end latency", + stats.UnitMilliseconds) +) + +// The following tags are applied to stats recorded by this package. Host, Path +// and Method are applied to all measures. StatusCode is not applied to +// ClientRequestCount or ServerRequestCount, since it is recorded before the status is known. +var ( + // Host is the value of the HTTP Host header. + // + // The value of this tag can be controlled by the HTTP client, so you need + // to watch out for potentially generating high-cardinality labels in your + // metrics backend if you use this tag in views. + Host, _ = tag.NewKey("http.host") + + // StatusCode is the numeric HTTP response status code, + // or "error" if a transport error occurred and no status code was read. + StatusCode, _ = tag.NewKey("http.status") + + // Path is the URL path (not including query string) in the request. + // + // The value of this tag can be controlled by the HTTP client, so you need + // to watch out for potentially generating high-cardinality labels in your + // metrics backend if you use this tag in views. + Path, _ = tag.NewKey("http.path") + + // Method is the HTTP method of the request, capitalized (GET, POST, etc.). + Method, _ = tag.NewKey("http.method") + + // KeyServerRoute is a low cardinality string representing the logical + // handler of the request. This is usually the pattern registered on the a + // ServeMux (or similar string). + KeyServerRoute, _ = tag.NewKey("http_server_route") +) + +// Client tag keys. +var ( + // KeyClientMethod is the HTTP method, capitalized (i.e. GET, POST, PUT, DELETE, etc.). + KeyClientMethod, _ = tag.NewKey("http_client_method") + // KeyClientPath is the URL path (not including query string). + KeyClientPath, _ = tag.NewKey("http_client_path") + // KeyClientStatus is the HTTP status code as an integer (e.g. 200, 404, 500.), or "error" if no response status line was received. + KeyClientStatus, _ = tag.NewKey("http_client_status") + // KeyClientHost is the value of the request Host header. + KeyClientHost, _ = tag.NewKey("http_client_host") +) + +// Default distributions used by views in this package. +var ( + DefaultSizeDistribution = view.Distribution(1024, 2048, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864, 268435456, 1073741824, 4294967296) + DefaultLatencyDistribution = view.Distribution(1, 2, 3, 4, 5, 6, 8, 10, 13, 16, 20, 25, 30, 40, 50, 65, 80, 100, 130, 160, 200, 250, 300, 400, 500, 650, 800, 1000, 2000, 5000, 10000, 20000, 50000, 100000) +) + +// Package ochttp provides some convenience views for client measures. +// You still need to register these views for data to actually be collected. +var ( + ClientSentBytesDistribution = &view.View{ + Name: "opencensus.io/http/client/sent_bytes", + Measure: ClientSentBytes, + Aggregation: DefaultSizeDistribution, + Description: "Total bytes sent in request body (not including headers), by HTTP method and response status", + TagKeys: []tag.Key{KeyClientMethod, KeyClientStatus}, + } + + ClientReceivedBytesDistribution = &view.View{ + Name: "opencensus.io/http/client/received_bytes", + Measure: ClientReceivedBytes, + Aggregation: DefaultSizeDistribution, + Description: "Total bytes received in response bodies (not including headers but including error responses with bodies), by HTTP method and response status", + TagKeys: []tag.Key{KeyClientMethod, KeyClientStatus}, + } + + ClientRoundtripLatencyDistribution = &view.View{ + Name: "opencensus.io/http/client/roundtrip_latency", + Measure: ClientRoundtripLatency, + Aggregation: DefaultLatencyDistribution, + Description: "End-to-end latency, by HTTP method and response status", + TagKeys: []tag.Key{KeyClientMethod, KeyClientStatus}, + } + + ClientCompletedCount = &view.View{ + Name: "opencensus.io/http/client/completed_count", + Measure: ClientRoundtripLatency, + Aggregation: view.Count(), + Description: "Count of completed requests, by HTTP method and response status", + TagKeys: []tag.Key{KeyClientMethod, KeyClientStatus}, + } +) + +// Deprecated: Old client Views. +var ( + // Deprecated: No direct replacement, but see ClientCompletedCount. + ClientRequestCountView = &view.View{ + Name: "opencensus.io/http/client/request_count", + Description: "Count of HTTP requests started", + Measure: ClientRequestCount, + Aggregation: view.Count(), + } + + // Deprecated: Use ClientSentBytesDistribution. + ClientRequestBytesView = &view.View{ + Name: "opencensus.io/http/client/request_bytes", + Description: "Size distribution of HTTP request body", + Measure: ClientSentBytes, + Aggregation: DefaultSizeDistribution, + } + + // Deprecated: Use ClientReceivedBytesDistribution instead. + ClientResponseBytesView = &view.View{ + Name: "opencensus.io/http/client/response_bytes", + Description: "Size distribution of HTTP response body", + Measure: ClientReceivedBytes, + Aggregation: DefaultSizeDistribution, + } + + // Deprecated: Use ClientRoundtripLatencyDistribution instead. + ClientLatencyView = &view.View{ + Name: "opencensus.io/http/client/latency", + Description: "Latency distribution of HTTP requests", + Measure: ClientRoundtripLatency, + Aggregation: DefaultLatencyDistribution, + } + + // Deprecated: Use ClientCompletedCount instead. + ClientRequestCountByMethod = &view.View{ + Name: "opencensus.io/http/client/request_count_by_method", + Description: "Client request count by HTTP method", + TagKeys: []tag.Key{Method}, + Measure: ClientSentBytes, + Aggregation: view.Count(), + } + + // Deprecated: Use ClientCompletedCount instead. + ClientResponseCountByStatusCode = &view.View{ + Name: "opencensus.io/http/client/response_count_by_status_code", + Description: "Client response count by status code", + TagKeys: []tag.Key{StatusCode}, + Measure: ClientRoundtripLatency, + Aggregation: view.Count(), + } +) + +// Package ochttp provides some convenience views for server measures. +// You still need to register these views for data to actually be collected. +var ( + ServerRequestCountView = &view.View{ + Name: "opencensus.io/http/server/request_count", + Description: "Count of HTTP requests started", + Measure: ServerRequestCount, + Aggregation: view.Count(), + } + + ServerRequestBytesView = &view.View{ + Name: "opencensus.io/http/server/request_bytes", + Description: "Size distribution of HTTP request body", + Measure: ServerRequestBytes, + Aggregation: DefaultSizeDistribution, + } + + ServerResponseBytesView = &view.View{ + Name: "opencensus.io/http/server/response_bytes", + Description: "Size distribution of HTTP response body", + Measure: ServerResponseBytes, + Aggregation: DefaultSizeDistribution, + } + + ServerLatencyView = &view.View{ + Name: "opencensus.io/http/server/latency", + Description: "Latency distribution of HTTP requests", + Measure: ServerLatency, + Aggregation: DefaultLatencyDistribution, + } + + ServerRequestCountByMethod = &view.View{ + Name: "opencensus.io/http/server/request_count_by_method", + Description: "Server request count by HTTP method", + TagKeys: []tag.Key{Method}, + Measure: ServerRequestCount, + Aggregation: view.Count(), + } + + ServerResponseCountByStatusCode = &view.View{ + Name: "opencensus.io/http/server/response_count_by_status_code", + Description: "Server response count by status code", + TagKeys: []tag.Key{StatusCode}, + Measure: ServerLatency, + Aggregation: view.Count(), + } +) + +// DefaultClientViews are the default client views provided by this package. +// Deprecated: No replacement. Register the views you would like individually. +var DefaultClientViews = []*view.View{ + ClientRequestCountView, + ClientRequestBytesView, + ClientResponseBytesView, + ClientLatencyView, + ClientRequestCountByMethod, + ClientResponseCountByStatusCode, +} + +// DefaultServerViews are the default server views provided by this package. +// Deprecated: No replacement. Register the views you would like individually. +var DefaultServerViews = []*view.View{ + ServerRequestCountView, + ServerRequestBytesView, + ServerResponseBytesView, + ServerLatencyView, + ServerRequestCountByMethod, + ServerResponseCountByStatusCode, +} diff --git a/vendor/go.opencensus.io/plugin/ochttp/trace.go b/vendor/go.opencensus.io/plugin/ochttp/trace.go new file mode 100644 index 00000000..c23b97fb --- /dev/null +++ b/vendor/go.opencensus.io/plugin/ochttp/trace.go @@ -0,0 +1,239 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package ochttp + +import ( + "io" + "net/http" + "net/http/httptrace" + + "go.opencensus.io/plugin/ochttp/propagation/b3" + "go.opencensus.io/trace" + "go.opencensus.io/trace/propagation" +) + +// TODO(jbd): Add godoc examples. + +var defaultFormat propagation.HTTPFormat = &b3.HTTPFormat{} + +// Attributes recorded on the span for the requests. +// Only trace exporters will need them. +const ( + HostAttribute = "http.host" + MethodAttribute = "http.method" + PathAttribute = "http.path" + URLAttribute = "http.url" + UserAgentAttribute = "http.user_agent" + StatusCodeAttribute = "http.status_code" +) + +type traceTransport struct { + base http.RoundTripper + startOptions trace.StartOptions + format propagation.HTTPFormat + formatSpanName func(*http.Request) string + newClientTrace func(*http.Request, *trace.Span) *httptrace.ClientTrace +} + +// TODO(jbd): Add message events for request and response size. + +// RoundTrip creates a trace.Span and inserts it into the outgoing request's headers. +// The created span can follow a parent span, if a parent is presented in +// the request's context. +func (t *traceTransport) RoundTrip(req *http.Request) (*http.Response, error) { + name := t.formatSpanName(req) + // TODO(jbd): Discuss whether we want to prefix + // outgoing requests with Sent. + ctx, span := trace.StartSpan(req.Context(), name, + trace.WithSampler(t.startOptions.Sampler), + trace.WithSpanKind(trace.SpanKindClient)) + + if t.newClientTrace != nil { + req = req.WithContext(httptrace.WithClientTrace(ctx, t.newClientTrace(req, span))) + } else { + req = req.WithContext(ctx) + } + + if t.format != nil { + // SpanContextToRequest will modify its Request argument, which is + // contrary to the contract for http.RoundTripper, so we need to + // pass it a copy of the Request. + // However, the Request struct itself was already copied by + // the WithContext calls above and so we just need to copy the header. + header := make(http.Header) + for k, v := range req.Header { + header[k] = v + } + req.Header = header + t.format.SpanContextToRequest(span.SpanContext(), req) + } + + span.AddAttributes(requestAttrs(req)...) + resp, err := t.base.RoundTrip(req) + if err != nil { + span.SetStatus(trace.Status{Code: trace.StatusCodeUnknown, Message: err.Error()}) + span.End() + return resp, err + } + + span.AddAttributes(responseAttrs(resp)...) + span.SetStatus(TraceStatus(resp.StatusCode, resp.Status)) + + // span.End() will be invoked after + // a read from resp.Body returns io.EOF or when + // resp.Body.Close() is invoked. + bt := &bodyTracker{rc: resp.Body, span: span} + resp.Body = wrappedBody(bt, resp.Body) + return resp, err +} + +// bodyTracker wraps a response.Body and invokes +// trace.EndSpan on encountering io.EOF on reading +// the body of the original response. +type bodyTracker struct { + rc io.ReadCloser + span *trace.Span +} + +var _ io.ReadCloser = (*bodyTracker)(nil) + +func (bt *bodyTracker) Read(b []byte) (int, error) { + n, err := bt.rc.Read(b) + + switch err { + case nil: + return n, nil + case io.EOF: + bt.span.End() + default: + // For all other errors, set the span status + bt.span.SetStatus(trace.Status{ + // Code 2 is the error code for Internal server error. + Code: 2, + Message: err.Error(), + }) + } + return n, err +} + +func (bt *bodyTracker) Close() error { + // Invoking endSpan on Close will help catch the cases + // in which a read returned a non-nil error, we set the + // span status but didn't end the span. + bt.span.End() + return bt.rc.Close() +} + +// CancelRequest cancels an in-flight request by closing its connection. +func (t *traceTransport) CancelRequest(req *http.Request) { + type canceler interface { + CancelRequest(*http.Request) + } + if cr, ok := t.base.(canceler); ok { + cr.CancelRequest(req) + } +} + +func spanNameFromURL(req *http.Request) string { + return req.URL.Path +} + +func requestAttrs(r *http.Request) []trace.Attribute { + userAgent := r.UserAgent() + + attrs := make([]trace.Attribute, 0, 5) + attrs = append(attrs, + trace.StringAttribute(PathAttribute, r.URL.Path), + trace.StringAttribute(URLAttribute, r.URL.String()), + trace.StringAttribute(HostAttribute, r.Host), + trace.StringAttribute(MethodAttribute, r.Method), + ) + + if userAgent != "" { + attrs = append(attrs, trace.StringAttribute(UserAgentAttribute, userAgent)) + } + + return attrs +} + +func responseAttrs(resp *http.Response) []trace.Attribute { + return []trace.Attribute{ + trace.Int64Attribute(StatusCodeAttribute, int64(resp.StatusCode)), + } +} + +// TraceStatus is a utility to convert the HTTP status code to a trace.Status that +// represents the outcome as closely as possible. +func TraceStatus(httpStatusCode int, statusLine string) trace.Status { + var code int32 + if httpStatusCode < 200 || httpStatusCode >= 400 { + code = trace.StatusCodeUnknown + } + switch httpStatusCode { + case 499: + code = trace.StatusCodeCancelled + case http.StatusBadRequest: + code = trace.StatusCodeInvalidArgument + case http.StatusGatewayTimeout: + code = trace.StatusCodeDeadlineExceeded + case http.StatusNotFound: + code = trace.StatusCodeNotFound + case http.StatusForbidden: + code = trace.StatusCodePermissionDenied + case http.StatusUnauthorized: // 401 is actually unauthenticated. + code = trace.StatusCodeUnauthenticated + case http.StatusTooManyRequests: + code = trace.StatusCodeResourceExhausted + case http.StatusNotImplemented: + code = trace.StatusCodeUnimplemented + case http.StatusServiceUnavailable: + code = trace.StatusCodeUnavailable + case http.StatusOK: + code = trace.StatusCodeOK + } + return trace.Status{Code: code, Message: codeToStr[code]} +} + +var codeToStr = map[int32]string{ + trace.StatusCodeOK: `OK`, + trace.StatusCodeCancelled: `CANCELLED`, + trace.StatusCodeUnknown: `UNKNOWN`, + trace.StatusCodeInvalidArgument: `INVALID_ARGUMENT`, + trace.StatusCodeDeadlineExceeded: `DEADLINE_EXCEEDED`, + trace.StatusCodeNotFound: `NOT_FOUND`, + trace.StatusCodeAlreadyExists: `ALREADY_EXISTS`, + trace.StatusCodePermissionDenied: `PERMISSION_DENIED`, + trace.StatusCodeResourceExhausted: `RESOURCE_EXHAUSTED`, + trace.StatusCodeFailedPrecondition: `FAILED_PRECONDITION`, + trace.StatusCodeAborted: `ABORTED`, + trace.StatusCodeOutOfRange: `OUT_OF_RANGE`, + trace.StatusCodeUnimplemented: `UNIMPLEMENTED`, + trace.StatusCodeInternal: `INTERNAL`, + trace.StatusCodeUnavailable: `UNAVAILABLE`, + trace.StatusCodeDataLoss: `DATA_LOSS`, + trace.StatusCodeUnauthenticated: `UNAUTHENTICATED`, +} + +func isHealthEndpoint(path string) bool { + // Health checking is pretty frequent and + // traces collected for health endpoints + // can be extremely noisy and expensive. + // Disable canonical health checking endpoints + // like /healthz and /_ah/health for now. + if path == "/healthz" || path == "/_ah/health" { + return true + } + return false +} diff --git a/vendor/go.opencensus.io/plugin/ochttp/wrapped_body.go b/vendor/go.opencensus.io/plugin/ochttp/wrapped_body.go new file mode 100644 index 00000000..7d75cae2 --- /dev/null +++ b/vendor/go.opencensus.io/plugin/ochttp/wrapped_body.go @@ -0,0 +1,44 @@ +// Copyright 2019, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package ochttp + +import ( + "io" +) + +// wrappedBody returns a wrapped version of the original +// Body and only implements the same combination of additional +// interfaces as the original. +func wrappedBody(wrapper io.ReadCloser, body io.ReadCloser) io.ReadCloser { + var ( + wr, i0 = body.(io.Writer) + ) + switch { + case !i0: + return struct { + io.ReadCloser + }{wrapper} + + case i0: + return struct { + io.ReadCloser + io.Writer + }{wrapper, wr} + default: + return struct { + io.ReadCloser + }{wrapper} + } +} diff --git a/vendor/go.opencensus.io/resource/resource.go b/vendor/go.opencensus.io/resource/resource.go new file mode 100644 index 00000000..b1764e1d --- /dev/null +++ b/vendor/go.opencensus.io/resource/resource.go @@ -0,0 +1,164 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package resource provides functionality for resource, which capture +// identifying information about the entities for which signals are exported. +package resource + +import ( + "context" + "fmt" + "os" + "regexp" + "sort" + "strconv" + "strings" +) + +// Environment variables used by FromEnv to decode a resource. +const ( + EnvVarType = "OC_RESOURCE_TYPE" + EnvVarLabels = "OC_RESOURCE_LABELS" +) + +// Resource describes an entity about which identifying information and metadata is exposed. +// For example, a type "k8s.io/container" may hold labels describing the pod name and namespace. +type Resource struct { + Type string + Labels map[string]string +} + +// EncodeLabels encodes a labels map to a string as provided via the OC_RESOURCE_LABELS environment variable. +func EncodeLabels(labels map[string]string) string { + sortedKeys := make([]string, 0, len(labels)) + for k := range labels { + sortedKeys = append(sortedKeys, k) + } + sort.Strings(sortedKeys) + + s := "" + for i, k := range sortedKeys { + if i > 0 { + s += "," + } + s += k + "=" + strconv.Quote(labels[k]) + } + return s +} + +var labelRegex = regexp.MustCompile(`^\s*([[:ascii:]]{1,256}?)=("[[:ascii:]]{0,256}?")\s*,`) + +// DecodeLabels decodes a serialized label map as used in the OC_RESOURCE_LABELS variable. +// A list of labels of the form `="",="",...` is accepted. +// Domain names and paths are accepted as label keys. +// Most users will want to use FromEnv instead. +func DecodeLabels(s string) (map[string]string, error) { + m := map[string]string{} + // Ensure a trailing comma, which allows us to keep the regex simpler + s = strings.TrimRight(strings.TrimSpace(s), ",") + "," + + for len(s) > 0 { + match := labelRegex.FindStringSubmatch(s) + if len(match) == 0 { + return nil, fmt.Errorf("invalid label formatting, remainder: %s", s) + } + v := match[2] + if v == "" { + v = match[3] + } else { + var err error + if v, err = strconv.Unquote(v); err != nil { + return nil, fmt.Errorf("invalid label formatting, remainder: %s, err: %s", s, err) + } + } + m[match[1]] = v + + s = s[len(match[0]):] + } + return m, nil +} + +// FromEnv is a detector that loads resource information from the OC_RESOURCE_TYPE +// and OC_RESOURCE_labelS environment variables. +func FromEnv(context.Context) (*Resource, error) { + res := &Resource{ + Type: strings.TrimSpace(os.Getenv(EnvVarType)), + } + labels := strings.TrimSpace(os.Getenv(EnvVarLabels)) + if labels == "" { + return res, nil + } + var err error + if res.Labels, err = DecodeLabels(labels); err != nil { + return nil, err + } + return res, nil +} + +var _ Detector = FromEnv + +// merge resource information from b into a. In case of a collision, a takes precedence. +func merge(a, b *Resource) *Resource { + if a == nil { + return b + } + if b == nil { + return a + } + res := &Resource{ + Type: a.Type, + Labels: map[string]string{}, + } + if res.Type == "" { + res.Type = b.Type + } + for k, v := range b.Labels { + res.Labels[k] = v + } + // Labels from resource a overwrite labels from resource b. + for k, v := range a.Labels { + res.Labels[k] = v + } + return res +} + +// Detector attempts to detect resource information. +// If the detector cannot find resource information, the returned resource is nil but no +// error is returned. +// An error is only returned on unexpected failures. +type Detector func(context.Context) (*Resource, error) + +// MultiDetector returns a Detector that calls all input detectors in order and +// merges each result with the previous one. In case a type of label key is already set, +// the first set value is takes precedence. +// It returns on the first error that a sub-detector encounters. +func MultiDetector(detectors ...Detector) Detector { + return func(ctx context.Context) (*Resource, error) { + return detectAll(ctx, detectors...) + } +} + +// detectall calls all input detectors sequentially an merges each result with the previous one. +// It returns on the first error that a sub-detector encounters. +func detectAll(ctx context.Context, detectors ...Detector) (*Resource, error) { + var res *Resource + for _, d := range detectors { + r, err := d(ctx) + if err != nil { + return nil, err + } + res = merge(res, r) + } + return res, nil +} diff --git a/vendor/go.opencensus.io/stats/doc.go b/vendor/go.opencensus.io/stats/doc.go new file mode 100644 index 00000000..00d473ee --- /dev/null +++ b/vendor/go.opencensus.io/stats/doc.go @@ -0,0 +1,69 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/* +Package stats contains support for OpenCensus stats recording. + +OpenCensus allows users to create typed measures, record measurements, +aggregate the collected data, and export the aggregated data. + +Measures + +A measure represents a type of data point to be tracked and recorded. +For example, latency, request Mb/s, and response Mb/s are measures +to collect from a server. + +Measure constructors such as Int64 and Float64 automatically +register the measure by the given name. Each registered measure needs +to be unique by name. Measures also have a description and a unit. + +Libraries can define and export measures. Application authors can then +create views and collect and break down measures by the tags they are +interested in. + +Recording measurements + +Measurement is a data point to be collected for a measure. For example, +for a latency (ms) measure, 100 is a measurement that represents a 100ms +latency event. Measurements are created from measures with +the current context. Tags from the current context are recorded with the +measurements if they are any. + +Recorded measurements are dropped immediately if no views are registered for them. +There is usually no need to conditionally enable and disable +recording to reduce cost. Recording of measurements is cheap. + +Libraries can always record measurements, and applications can later decide +on which measurements they want to collect by registering views. This allows +libraries to turn on the instrumentation by default. + +Exemplars + +For a given recorded measurement, the associated exemplar is a diagnostic map +that gives more information about the measurement. + +When aggregated using a Distribution aggregation, an exemplar is kept for each +bucket in the Distribution. This allows you to easily find an example of a +measurement that fell into each bucket. + +For example, if you also use the OpenCensus trace package and you +record a measurement with a context that contains a sampled trace span, +then the trace span will be added to the exemplar associated with the measurement. + +When exported to a supporting back end, you should be able to easily navigate +to example traces that fell into each bucket in the Distribution. + +*/ +package stats // import "go.opencensus.io/stats" diff --git a/vendor/go.opencensus.io/stats/internal/record.go b/vendor/go.opencensus.io/stats/internal/record.go new file mode 100644 index 00000000..36935e62 --- /dev/null +++ b/vendor/go.opencensus.io/stats/internal/record.go @@ -0,0 +1,25 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package internal + +import ( + "go.opencensus.io/tag" +) + +// DefaultRecorder will be called for each Record call. +var DefaultRecorder func(tags *tag.Map, measurement interface{}, attachments map[string]interface{}) + +// SubscriptionReporter reports when a view subscribed with a measure. +var SubscriptionReporter func(measure string) diff --git a/vendor/go.opencensus.io/stats/measure.go b/vendor/go.opencensus.io/stats/measure.go new file mode 100644 index 00000000..1ffd3cef --- /dev/null +++ b/vendor/go.opencensus.io/stats/measure.go @@ -0,0 +1,109 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package stats + +import ( + "sync" + "sync/atomic" +) + +// Measure represents a single numeric value to be tracked and recorded. +// For example, latency, request bytes, and response bytes could be measures +// to collect from a server. +// +// Measures by themselves have no outside effects. In order to be exported, +// the measure needs to be used in a View. If no Views are defined over a +// measure, there is very little cost in recording it. +type Measure interface { + // Name returns the name of this measure. + // + // Measure names are globally unique (among all libraries linked into your program). + // We recommend prefixing the measure name with a domain name relevant to your + // project or application. + // + // Measure names are never sent over the wire or exported to backends. + // They are only used to create Views. + Name() string + + // Description returns the human-readable description of this measure. + Description() string + + // Unit returns the units for the values this measure takes on. + // + // Units are encoded according to the case-sensitive abbreviations from the + // Unified Code for Units of Measure: http://unitsofmeasure.org/ucum.html + Unit() string +} + +// measureDescriptor is the untyped descriptor associated with each measure. +// Int64Measure and Float64Measure wrap measureDescriptor to provide typed +// recording APIs. +// Two Measures with the same name will have the same measureDescriptor. +type measureDescriptor struct { + subs int32 // access atomically + + name string + description string + unit string +} + +func (m *measureDescriptor) subscribe() { + atomic.StoreInt32(&m.subs, 1) +} + +func (m *measureDescriptor) subscribed() bool { + return atomic.LoadInt32(&m.subs) == 1 +} + +var ( + mu sync.RWMutex + measures = make(map[string]*measureDescriptor) +) + +func registerMeasureHandle(name, desc, unit string) *measureDescriptor { + mu.Lock() + defer mu.Unlock() + + if stored, ok := measures[name]; ok { + return stored + } + m := &measureDescriptor{ + name: name, + description: desc, + unit: unit, + } + measures[name] = m + return m +} + +// Measurement is the numeric value measured when recording stats. Each measure +// provides methods to create measurements of their kind. For example, Int64Measure +// provides M to convert an int64 into a measurement. +type Measurement struct { + v float64 + m Measure + desc *measureDescriptor +} + +// Value returns the value of the Measurement as a float64. +func (m Measurement) Value() float64 { + return m.v +} + +// Measure returns the Measure from which this Measurement was created. +func (m Measurement) Measure() Measure { + return m.m +} diff --git a/vendor/go.opencensus.io/stats/measure_float64.go b/vendor/go.opencensus.io/stats/measure_float64.go new file mode 100644 index 00000000..f02c1eda --- /dev/null +++ b/vendor/go.opencensus.io/stats/measure_float64.go @@ -0,0 +1,55 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package stats + +// Float64Measure is a measure for float64 values. +type Float64Measure struct { + desc *measureDescriptor +} + +// M creates a new float64 measurement. +// Use Record to record measurements. +func (m *Float64Measure) M(v float64) Measurement { + return Measurement{ + m: m, + desc: m.desc, + v: v, + } +} + +// Float64 creates a new measure for float64 values. +// +// See the documentation for interface Measure for more guidance on the +// parameters of this function. +func Float64(name, description, unit string) *Float64Measure { + mi := registerMeasureHandle(name, description, unit) + return &Float64Measure{mi} +} + +// Name returns the name of the measure. +func (m *Float64Measure) Name() string { + return m.desc.name +} + +// Description returns the description of the measure. +func (m *Float64Measure) Description() string { + return m.desc.description +} + +// Unit returns the unit of the measure. +func (m *Float64Measure) Unit() string { + return m.desc.unit +} diff --git a/vendor/go.opencensus.io/stats/measure_int64.go b/vendor/go.opencensus.io/stats/measure_int64.go new file mode 100644 index 00000000..d101d797 --- /dev/null +++ b/vendor/go.opencensus.io/stats/measure_int64.go @@ -0,0 +1,55 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package stats + +// Int64Measure is a measure for int64 values. +type Int64Measure struct { + desc *measureDescriptor +} + +// M creates a new int64 measurement. +// Use Record to record measurements. +func (m *Int64Measure) M(v int64) Measurement { + return Measurement{ + m: m, + desc: m.desc, + v: float64(v), + } +} + +// Int64 creates a new measure for int64 values. +// +// See the documentation for interface Measure for more guidance on the +// parameters of this function. +func Int64(name, description, unit string) *Int64Measure { + mi := registerMeasureHandle(name, description, unit) + return &Int64Measure{mi} +} + +// Name returns the name of the measure. +func (m *Int64Measure) Name() string { + return m.desc.name +} + +// Description returns the description of the measure. +func (m *Int64Measure) Description() string { + return m.desc.description +} + +// Unit returns the unit of the measure. +func (m *Int64Measure) Unit() string { + return m.desc.unit +} diff --git a/vendor/go.opencensus.io/stats/record.go b/vendor/go.opencensus.io/stats/record.go new file mode 100644 index 00000000..ad469118 --- /dev/null +++ b/vendor/go.opencensus.io/stats/record.go @@ -0,0 +1,117 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package stats + +import ( + "context" + + "go.opencensus.io/metric/metricdata" + "go.opencensus.io/stats/internal" + "go.opencensus.io/tag" +) + +func init() { + internal.SubscriptionReporter = func(measure string) { + mu.Lock() + measures[measure].subscribe() + mu.Unlock() + } +} + +type recordOptions struct { + attachments metricdata.Attachments + mutators []tag.Mutator + measurements []Measurement +} + +// WithAttachments applies provided exemplar attachments. +func WithAttachments(attachments metricdata.Attachments) Options { + return func(ro *recordOptions) { + ro.attachments = attachments + } +} + +// WithTags applies provided tag mutators. +func WithTags(mutators ...tag.Mutator) Options { + return func(ro *recordOptions) { + ro.mutators = mutators + } +} + +// WithMeasurements applies provided measurements. +func WithMeasurements(measurements ...Measurement) Options { + return func(ro *recordOptions) { + ro.measurements = measurements + } +} + +// Options apply changes to recordOptions. +type Options func(*recordOptions) + +func createRecordOption(ros ...Options) *recordOptions { + o := &recordOptions{} + for _, ro := range ros { + ro(o) + } + return o +} + +// Record records one or multiple measurements with the same context at once. +// If there are any tags in the context, measurements will be tagged with them. +func Record(ctx context.Context, ms ...Measurement) { + RecordWithOptions(ctx, WithMeasurements(ms...)) +} + +// RecordWithTags records one or multiple measurements at once. +// +// Measurements will be tagged with the tags in the context mutated by the mutators. +// RecordWithTags is useful if you want to record with tag mutations but don't want +// to propagate the mutations in the context. +func RecordWithTags(ctx context.Context, mutators []tag.Mutator, ms ...Measurement) error { + return RecordWithOptions(ctx, WithTags(mutators...), WithMeasurements(ms...)) +} + +// RecordWithOptions records measurements from the given options (if any) against context +// and tags and attachments in the options (if any). +// If there are any tags in the context, measurements will be tagged with them. +func RecordWithOptions(ctx context.Context, ros ...Options) error { + o := createRecordOption(ros...) + if len(o.measurements) == 0 { + return nil + } + recorder := internal.DefaultRecorder + if recorder == nil { + return nil + } + record := false + for _, m := range o.measurements { + if m.desc.subscribed() { + record = true + break + } + } + if !record { + return nil + } + if len(o.mutators) > 0 { + var err error + if ctx, err = tag.New(ctx, o.mutators...); err != nil { + return err + } + } + recorder(tag.FromContext(ctx), o.measurements, o.attachments) + return nil +} diff --git a/vendor/go.opencensus.io/stats/units.go b/vendor/go.opencensus.io/stats/units.go new file mode 100644 index 00000000..6931a5f2 --- /dev/null +++ b/vendor/go.opencensus.io/stats/units.go @@ -0,0 +1,25 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package stats + +// Units are encoded according to the case-sensitive abbreviations from the +// Unified Code for Units of Measure: http://unitsofmeasure.org/ucum.html +const ( + UnitNone = "1" // Deprecated: Use UnitDimensionless. + UnitDimensionless = "1" + UnitBytes = "By" + UnitMilliseconds = "ms" +) diff --git a/vendor/go.opencensus.io/stats/view/aggregation.go b/vendor/go.opencensus.io/stats/view/aggregation.go new file mode 100644 index 00000000..b7f169b4 --- /dev/null +++ b/vendor/go.opencensus.io/stats/view/aggregation.go @@ -0,0 +1,120 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package view + +// AggType represents the type of aggregation function used on a View. +type AggType int + +// All available aggregation types. +const ( + AggTypeNone AggType = iota // no aggregation; reserved for future use. + AggTypeCount // the count aggregation, see Count. + AggTypeSum // the sum aggregation, see Sum. + AggTypeDistribution // the distribution aggregation, see Distribution. + AggTypeLastValue // the last value aggregation, see LastValue. +) + +func (t AggType) String() string { + return aggTypeName[t] +} + +var aggTypeName = map[AggType]string{ + AggTypeNone: "None", + AggTypeCount: "Count", + AggTypeSum: "Sum", + AggTypeDistribution: "Distribution", + AggTypeLastValue: "LastValue", +} + +// Aggregation represents a data aggregation method. Use one of the functions: +// Count, Sum, or Distribution to construct an Aggregation. +type Aggregation struct { + Type AggType // Type is the AggType of this Aggregation. + Buckets []float64 // Buckets are the bucket endpoints if this Aggregation represents a distribution, see Distribution. + + newData func() AggregationData +} + +var ( + aggCount = &Aggregation{ + Type: AggTypeCount, + newData: func() AggregationData { + return &CountData{} + }, + } + aggSum = &Aggregation{ + Type: AggTypeSum, + newData: func() AggregationData { + return &SumData{} + }, + } +) + +// Count indicates that data collected and aggregated +// with this method will be turned into a count value. +// For example, total number of accepted requests can be +// aggregated by using Count. +func Count() *Aggregation { + return aggCount +} + +// Sum indicates that data collected and aggregated +// with this method will be summed up. +// For example, accumulated request bytes can be aggregated by using +// Sum. +func Sum() *Aggregation { + return aggSum +} + +// Distribution indicates that the desired aggregation is +// a histogram distribution. +// +// An distribution aggregation may contain a histogram of the values in the +// population. The bucket boundaries for that histogram are described +// by the bounds. This defines len(bounds)+1 buckets. +// +// If len(bounds) >= 2 then the boundaries for bucket index i are: +// +// [-infinity, bounds[i]) for i = 0 +// [bounds[i-1], bounds[i]) for 0 < i < length +// [bounds[i-1], +infinity) for i = length +// +// If len(bounds) is 0 then there is no histogram associated with the +// distribution. There will be a single bucket with boundaries +// (-infinity, +infinity). +// +// If len(bounds) is 1 then there is no finite buckets, and that single +// element is the common boundary of the overflow and underflow buckets. +func Distribution(bounds ...float64) *Aggregation { + return &Aggregation{ + Type: AggTypeDistribution, + Buckets: bounds, + newData: func() AggregationData { + return newDistributionData(bounds) + }, + } +} + +// LastValue only reports the last value recorded using this +// aggregation. All other measurements will be dropped. +func LastValue() *Aggregation { + return &Aggregation{ + Type: AggTypeLastValue, + newData: func() AggregationData { + return &LastValueData{} + }, + } +} diff --git a/vendor/go.opencensus.io/stats/view/aggregation_data.go b/vendor/go.opencensus.io/stats/view/aggregation_data.go new file mode 100644 index 00000000..d500e67f --- /dev/null +++ b/vendor/go.opencensus.io/stats/view/aggregation_data.go @@ -0,0 +1,293 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package view + +import ( + "math" + "time" + + "go.opencensus.io/metric/metricdata" +) + +// AggregationData represents an aggregated value from a collection. +// They are reported on the view data during exporting. +// Mosts users won't directly access aggregration data. +type AggregationData interface { + isAggregationData() bool + addSample(v float64, attachments map[string]interface{}, t time.Time) + clone() AggregationData + equal(other AggregationData) bool + toPoint(t metricdata.Type, time time.Time) metricdata.Point +} + +const epsilon = 1e-9 + +// CountData is the aggregated data for the Count aggregation. +// A count aggregation processes data and counts the recordings. +// +// Most users won't directly access count data. +type CountData struct { + Value int64 +} + +func (a *CountData) isAggregationData() bool { return true } + +func (a *CountData) addSample(_ float64, _ map[string]interface{}, _ time.Time) { + a.Value = a.Value + 1 +} + +func (a *CountData) clone() AggregationData { + return &CountData{Value: a.Value} +} + +func (a *CountData) equal(other AggregationData) bool { + a2, ok := other.(*CountData) + if !ok { + return false + } + + return a.Value == a2.Value +} + +func (a *CountData) toPoint(metricType metricdata.Type, t time.Time) metricdata.Point { + switch metricType { + case metricdata.TypeCumulativeInt64: + return metricdata.NewInt64Point(t, a.Value) + default: + panic("unsupported metricdata.Type") + } +} + +// SumData is the aggregated data for the Sum aggregation. +// A sum aggregation processes data and sums up the recordings. +// +// Most users won't directly access sum data. +type SumData struct { + Value float64 +} + +func (a *SumData) isAggregationData() bool { return true } + +func (a *SumData) addSample(v float64, _ map[string]interface{}, _ time.Time) { + a.Value += v +} + +func (a *SumData) clone() AggregationData { + return &SumData{Value: a.Value} +} + +func (a *SumData) equal(other AggregationData) bool { + a2, ok := other.(*SumData) + if !ok { + return false + } + return math.Pow(a.Value-a2.Value, 2) < epsilon +} + +func (a *SumData) toPoint(metricType metricdata.Type, t time.Time) metricdata.Point { + switch metricType { + case metricdata.TypeCumulativeInt64: + return metricdata.NewInt64Point(t, int64(a.Value)) + case metricdata.TypeCumulativeFloat64: + return metricdata.NewFloat64Point(t, a.Value) + default: + panic("unsupported metricdata.Type") + } +} + +// DistributionData is the aggregated data for the +// Distribution aggregation. +// +// Most users won't directly access distribution data. +// +// For a distribution with N bounds, the associated DistributionData will have +// N+1 buckets. +type DistributionData struct { + Count int64 // number of data points aggregated + Min float64 // minimum value in the distribution + Max float64 // max value in the distribution + Mean float64 // mean of the distribution + SumOfSquaredDev float64 // sum of the squared deviation from the mean + CountPerBucket []int64 // number of occurrences per bucket + // ExemplarsPerBucket is slice the same length as CountPerBucket containing + // an exemplar for the associated bucket, or nil. + ExemplarsPerBucket []*metricdata.Exemplar + bounds []float64 // histogram distribution of the values +} + +func newDistributionData(bounds []float64) *DistributionData { + bucketCount := len(bounds) + 1 + return &DistributionData{ + CountPerBucket: make([]int64, bucketCount), + ExemplarsPerBucket: make([]*metricdata.Exemplar, bucketCount), + bounds: bounds, + Min: math.MaxFloat64, + Max: math.SmallestNonzeroFloat64, + } +} + +// Sum returns the sum of all samples collected. +func (a *DistributionData) Sum() float64 { return a.Mean * float64(a.Count) } + +func (a *DistributionData) variance() float64 { + if a.Count <= 1 { + return 0 + } + return a.SumOfSquaredDev / float64(a.Count-1) +} + +func (a *DistributionData) isAggregationData() bool { return true } + +// TODO(songy23): support exemplar attachments. +func (a *DistributionData) addSample(v float64, attachments map[string]interface{}, t time.Time) { + if v < a.Min { + a.Min = v + } + if v > a.Max { + a.Max = v + } + a.Count++ + a.addToBucket(v, attachments, t) + + if a.Count == 1 { + a.Mean = v + return + } + + oldMean := a.Mean + a.Mean = a.Mean + (v-a.Mean)/float64(a.Count) + a.SumOfSquaredDev = a.SumOfSquaredDev + (v-oldMean)*(v-a.Mean) +} + +func (a *DistributionData) addToBucket(v float64, attachments map[string]interface{}, t time.Time) { + var count *int64 + var i int + var b float64 + for i, b = range a.bounds { + if v < b { + count = &a.CountPerBucket[i] + break + } + } + if count == nil { // Last bucket. + i = len(a.bounds) + count = &a.CountPerBucket[i] + } + *count++ + if exemplar := getExemplar(v, attachments, t); exemplar != nil { + a.ExemplarsPerBucket[i] = exemplar + } +} + +func getExemplar(v float64, attachments map[string]interface{}, t time.Time) *metricdata.Exemplar { + if len(attachments) == 0 { + return nil + } + return &metricdata.Exemplar{ + Value: v, + Timestamp: t, + Attachments: attachments, + } +} + +func (a *DistributionData) clone() AggregationData { + c := *a + c.CountPerBucket = append([]int64(nil), a.CountPerBucket...) + c.ExemplarsPerBucket = append([]*metricdata.Exemplar(nil), a.ExemplarsPerBucket...) + return &c +} + +func (a *DistributionData) equal(other AggregationData) bool { + a2, ok := other.(*DistributionData) + if !ok { + return false + } + if a2 == nil { + return false + } + if len(a.CountPerBucket) != len(a2.CountPerBucket) { + return false + } + for i := range a.CountPerBucket { + if a.CountPerBucket[i] != a2.CountPerBucket[i] { + return false + } + } + return a.Count == a2.Count && a.Min == a2.Min && a.Max == a2.Max && math.Pow(a.Mean-a2.Mean, 2) < epsilon && math.Pow(a.variance()-a2.variance(), 2) < epsilon +} + +func (a *DistributionData) toPoint(metricType metricdata.Type, t time.Time) metricdata.Point { + switch metricType { + case metricdata.TypeCumulativeDistribution: + buckets := []metricdata.Bucket{} + for i := 0; i < len(a.CountPerBucket); i++ { + buckets = append(buckets, metricdata.Bucket{ + Count: a.CountPerBucket[i], + Exemplar: a.ExemplarsPerBucket[i], + }) + } + bucketOptions := &metricdata.BucketOptions{Bounds: a.bounds} + + val := &metricdata.Distribution{ + Count: a.Count, + Sum: a.Sum(), + SumOfSquaredDeviation: a.SumOfSquaredDev, + BucketOptions: bucketOptions, + Buckets: buckets, + } + return metricdata.NewDistributionPoint(t, val) + + default: + // TODO: [rghetia] when we have a use case for TypeGaugeDistribution. + panic("unsupported metricdata.Type") + } +} + +// LastValueData returns the last value recorded for LastValue aggregation. +type LastValueData struct { + Value float64 +} + +func (l *LastValueData) isAggregationData() bool { + return true +} + +func (l *LastValueData) addSample(v float64, _ map[string]interface{}, _ time.Time) { + l.Value = v +} + +func (l *LastValueData) clone() AggregationData { + return &LastValueData{l.Value} +} + +func (l *LastValueData) equal(other AggregationData) bool { + a2, ok := other.(*LastValueData) + if !ok { + return false + } + return l.Value == a2.Value +} + +func (l *LastValueData) toPoint(metricType metricdata.Type, t time.Time) metricdata.Point { + switch metricType { + case metricdata.TypeGaugeInt64: + return metricdata.NewInt64Point(t, int64(l.Value)) + case metricdata.TypeGaugeFloat64: + return metricdata.NewFloat64Point(t, l.Value) + default: + panic("unsupported metricdata.Type") + } +} diff --git a/vendor/go.opencensus.io/stats/view/collector.go b/vendor/go.opencensus.io/stats/view/collector.go new file mode 100644 index 00000000..8a6a2c0f --- /dev/null +++ b/vendor/go.opencensus.io/stats/view/collector.go @@ -0,0 +1,86 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package view + +import ( + "sort" + "time" + + "go.opencensus.io/internal/tagencoding" + "go.opencensus.io/tag" +) + +type collector struct { + // signatures holds the aggregations values for each unique tag signature + // (values for all keys) to its aggregator. + signatures map[string]AggregationData + // Aggregation is the description of the aggregation to perform for this + // view. + a *Aggregation +} + +func (c *collector) addSample(s string, v float64, attachments map[string]interface{}, t time.Time) { + aggregator, ok := c.signatures[s] + if !ok { + aggregator = c.a.newData() + c.signatures[s] = aggregator + } + aggregator.addSample(v, attachments, t) +} + +// collectRows returns a snapshot of the collected Row values. +func (c *collector) collectedRows(keys []tag.Key) []*Row { + rows := make([]*Row, 0, len(c.signatures)) + for sig, aggregator := range c.signatures { + tags := decodeTags([]byte(sig), keys) + row := &Row{Tags: tags, Data: aggregator.clone()} + rows = append(rows, row) + } + return rows +} + +func (c *collector) clearRows() { + c.signatures = make(map[string]AggregationData) +} + +// encodeWithKeys encodes the map by using values +// only associated with the keys provided. +func encodeWithKeys(m *tag.Map, keys []tag.Key) []byte { + vb := &tagencoding.Values{ + Buffer: make([]byte, len(keys)), + } + for _, k := range keys { + v, _ := m.Value(k) + vb.WriteValue([]byte(v)) + } + return vb.Bytes() +} + +// decodeTags decodes tags from the buffer and +// orders them by the keys. +func decodeTags(buf []byte, keys []tag.Key) []tag.Tag { + vb := &tagencoding.Values{Buffer: buf} + var tags []tag.Tag + for _, k := range keys { + v := vb.ReadValue() + if v != nil { + tags = append(tags, tag.Tag{Key: k, Value: string(v)}) + } + } + vb.ReadIndex = 0 + sort.Slice(tags, func(i, j int) bool { return tags[i].Key.Name() < tags[j].Key.Name() }) + return tags +} diff --git a/vendor/go.opencensus.io/stats/view/doc.go b/vendor/go.opencensus.io/stats/view/doc.go new file mode 100644 index 00000000..dced225c --- /dev/null +++ b/vendor/go.opencensus.io/stats/view/doc.go @@ -0,0 +1,47 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// Package view contains support for collecting and exposing aggregates over stats. +// +// In order to collect measurements, views need to be defined and registered. +// A view allows recorded measurements to be filtered and aggregated. +// +// All recorded measurements can be grouped by a list of tags. +// +// OpenCensus provides several aggregation methods: Count, Distribution and Sum. +// +// Count only counts the number of measurement points recorded. +// Distribution provides statistical summary of the aggregated data by counting +// how many recorded measurements fall into each bucket. +// Sum adds up the measurement values. +// LastValue just keeps track of the most recently recorded measurement value. +// All aggregations are cumulative. +// +// Views can be registerd and unregistered at any time during program execution. +// +// Libraries can define views but it is recommended that in most cases registering +// views be left up to applications. +// +// Exporting +// +// Collected and aggregated data can be exported to a metric collection +// backend by registering its exporter. +// +// Multiple exporters can be registered to upload the data to various +// different back ends. +package view // import "go.opencensus.io/stats/view" + +// TODO(acetechnologist): Add a link to the language independent OpenCensus +// spec when it is available. diff --git a/vendor/go.opencensus.io/stats/view/export.go b/vendor/go.opencensus.io/stats/view/export.go new file mode 100644 index 00000000..7cb59718 --- /dev/null +++ b/vendor/go.opencensus.io/stats/view/export.go @@ -0,0 +1,58 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package view + +import "sync" + +var ( + exportersMu sync.RWMutex // guards exporters + exporters = make(map[Exporter]struct{}) +) + +// Exporter exports the collected records as view data. +// +// The ExportView method should return quickly; if an +// Exporter takes a significant amount of time to +// process a Data, that work should be done on another goroutine. +// +// It is safe to assume that ExportView will not be called concurrently from +// multiple goroutines. +// +// The Data should not be modified. +type Exporter interface { + ExportView(viewData *Data) +} + +// RegisterExporter registers an exporter. +// Collected data will be reported via all the +// registered exporters. Once you no longer +// want data to be exported, invoke UnregisterExporter +// with the previously registered exporter. +// +// Binaries can register exporters, libraries shouldn't register exporters. +func RegisterExporter(e Exporter) { + exportersMu.Lock() + defer exportersMu.Unlock() + + exporters[e] = struct{}{} +} + +// UnregisterExporter unregisters an exporter. +func UnregisterExporter(e Exporter) { + exportersMu.Lock() + defer exportersMu.Unlock() + + delete(exporters, e) +} diff --git a/vendor/go.opencensus.io/stats/view/view.go b/vendor/go.opencensus.io/stats/view/view.go new file mode 100644 index 00000000..37f88e1d --- /dev/null +++ b/vendor/go.opencensus.io/stats/view/view.go @@ -0,0 +1,221 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package view + +import ( + "bytes" + "errors" + "fmt" + "reflect" + "sort" + "sync/atomic" + "time" + + "go.opencensus.io/metric/metricdata" + "go.opencensus.io/stats" + "go.opencensus.io/tag" +) + +// View allows users to aggregate the recorded stats.Measurements. +// Views need to be passed to the Register function to be before data will be +// collected and sent to Exporters. +type View struct { + Name string // Name of View. Must be unique. If unset, will default to the name of the Measure. + Description string // Description is a human-readable description for this view. + + // TagKeys are the tag keys describing the grouping of this view. + // A single Row will be produced for each combination of associated tag values. + TagKeys []tag.Key + + // Measure is a stats.Measure to aggregate in this view. + Measure stats.Measure + + // Aggregation is the aggregation function tp apply to the set of Measurements. + Aggregation *Aggregation +} + +// WithName returns a copy of the View with a new name. This is useful for +// renaming views to cope with limitations placed on metric names by various +// backends. +func (v *View) WithName(name string) *View { + vNew := *v + vNew.Name = name + return &vNew +} + +// same compares two views and returns true if they represent the same aggregation. +func (v *View) same(other *View) bool { + if v == other { + return true + } + if v == nil { + return false + } + return reflect.DeepEqual(v.Aggregation, other.Aggregation) && + v.Measure.Name() == other.Measure.Name() +} + +// ErrNegativeBucketBounds error returned if histogram contains negative bounds. +// +// Deprecated: this should not be public. +var ErrNegativeBucketBounds = errors.New("negative bucket bounds not supported") + +// canonicalize canonicalizes v by setting explicit +// defaults for Name and Description and sorting the TagKeys +func (v *View) canonicalize() error { + if v.Measure == nil { + return fmt.Errorf("cannot register view %q: measure not set", v.Name) + } + if v.Aggregation == nil { + return fmt.Errorf("cannot register view %q: aggregation not set", v.Name) + } + if v.Name == "" { + v.Name = v.Measure.Name() + } + if v.Description == "" { + v.Description = v.Measure.Description() + } + if err := checkViewName(v.Name); err != nil { + return err + } + sort.Slice(v.TagKeys, func(i, j int) bool { + return v.TagKeys[i].Name() < v.TagKeys[j].Name() + }) + sort.Float64s(v.Aggregation.Buckets) + for _, b := range v.Aggregation.Buckets { + if b < 0 { + return ErrNegativeBucketBounds + } + } + // drop 0 bucket silently. + v.Aggregation.Buckets = dropZeroBounds(v.Aggregation.Buckets...) + + return nil +} + +func dropZeroBounds(bounds ...float64) []float64 { + for i, bound := range bounds { + if bound > 0 { + return bounds[i:] + } + } + return []float64{} +} + +// viewInternal is the internal representation of a View. +type viewInternal struct { + view *View // view is the canonicalized View definition associated with this view. + subscribed uint32 // 1 if someone is subscribed and data need to be exported, use atomic to access + collector *collector + metricDescriptor *metricdata.Descriptor +} + +func newViewInternal(v *View) (*viewInternal, error) { + return &viewInternal{ + view: v, + collector: &collector{make(map[string]AggregationData), v.Aggregation}, + metricDescriptor: viewToMetricDescriptor(v), + }, nil +} + +func (v *viewInternal) subscribe() { + atomic.StoreUint32(&v.subscribed, 1) +} + +func (v *viewInternal) unsubscribe() { + atomic.StoreUint32(&v.subscribed, 0) +} + +// isSubscribed returns true if the view is exporting +// data by subscription. +func (v *viewInternal) isSubscribed() bool { + return atomic.LoadUint32(&v.subscribed) == 1 +} + +func (v *viewInternal) clearRows() { + v.collector.clearRows() +} + +func (v *viewInternal) collectedRows() []*Row { + return v.collector.collectedRows(v.view.TagKeys) +} + +func (v *viewInternal) addSample(m *tag.Map, val float64, attachments map[string]interface{}, t time.Time) { + if !v.isSubscribed() { + return + } + sig := string(encodeWithKeys(m, v.view.TagKeys)) + v.collector.addSample(sig, val, attachments, t) +} + +// A Data is a set of rows about usage of the single measure associated +// with the given view. Each row is specific to a unique set of tags. +type Data struct { + View *View + Start, End time.Time + Rows []*Row +} + +// Row is the collected value for a specific set of key value pairs a.k.a tags. +type Row struct { + Tags []tag.Tag + Data AggregationData +} + +func (r *Row) String() string { + var buffer bytes.Buffer + buffer.WriteString("{ ") + buffer.WriteString("{ ") + for _, t := range r.Tags { + buffer.WriteString(fmt.Sprintf("{%v %v}", t.Key.Name(), t.Value)) + } + buffer.WriteString(" }") + buffer.WriteString(fmt.Sprintf("%v", r.Data)) + buffer.WriteString(" }") + return buffer.String() +} + +// Equal returns true if both rows are equal. Tags are expected to be ordered +// by the key name. Even both rows have the same tags but the tags appear in +// different orders it will return false. +func (r *Row) Equal(other *Row) bool { + if r == other { + return true + } + return reflect.DeepEqual(r.Tags, other.Tags) && r.Data.equal(other.Data) +} + +const maxNameLength = 255 + +// Returns true if the given string contains only printable characters. +func isPrintable(str string) bool { + for _, r := range str { + if !(r >= ' ' && r <= '~') { + return false + } + } + return true +} + +func checkViewName(name string) error { + if len(name) > maxNameLength { + return fmt.Errorf("view name cannot be larger than %v", maxNameLength) + } + if !isPrintable(name) { + return fmt.Errorf("view name needs to be an ASCII string") + } + return nil +} diff --git a/vendor/go.opencensus.io/stats/view/view_to_metric.go b/vendor/go.opencensus.io/stats/view/view_to_metric.go new file mode 100644 index 00000000..010f81ba --- /dev/null +++ b/vendor/go.opencensus.io/stats/view/view_to_metric.go @@ -0,0 +1,140 @@ +// Copyright 2019, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package view + +import ( + "time" + + "go.opencensus.io/metric/metricdata" + "go.opencensus.io/stats" +) + +func getUnit(unit string) metricdata.Unit { + switch unit { + case "1": + return metricdata.UnitDimensionless + case "ms": + return metricdata.UnitMilliseconds + case "By": + return metricdata.UnitBytes + } + return metricdata.UnitDimensionless +} + +func getType(v *View) metricdata.Type { + m := v.Measure + agg := v.Aggregation + + switch agg.Type { + case AggTypeSum: + switch m.(type) { + case *stats.Int64Measure: + return metricdata.TypeCumulativeInt64 + case *stats.Float64Measure: + return metricdata.TypeCumulativeFloat64 + default: + panic("unexpected measure type") + } + case AggTypeDistribution: + return metricdata.TypeCumulativeDistribution + case AggTypeLastValue: + switch m.(type) { + case *stats.Int64Measure: + return metricdata.TypeGaugeInt64 + case *stats.Float64Measure: + return metricdata.TypeGaugeFloat64 + default: + panic("unexpected measure type") + } + case AggTypeCount: + switch m.(type) { + case *stats.Int64Measure: + return metricdata.TypeCumulativeInt64 + case *stats.Float64Measure: + return metricdata.TypeCumulativeInt64 + default: + panic("unexpected measure type") + } + default: + panic("unexpected aggregation type") + } +} + +func getLableKeys(v *View) []metricdata.LabelKey { + labelKeys := []metricdata.LabelKey{} + for _, k := range v.TagKeys { + labelKeys = append(labelKeys, metricdata.LabelKey{Key: k.Name()}) + } + return labelKeys +} + +func viewToMetricDescriptor(v *View) *metricdata.Descriptor { + return &metricdata.Descriptor{ + Name: v.Name, + Description: v.Description, + Unit: getUnit(v.Measure.Unit()), + Type: getType(v), + LabelKeys: getLableKeys(v), + } +} + +func toLabelValues(row *Row, expectedKeys []metricdata.LabelKey) []metricdata.LabelValue { + labelValues := []metricdata.LabelValue{} + tagMap := make(map[string]string) + for _, tag := range row.Tags { + tagMap[tag.Key.Name()] = tag.Value + } + + for _, key := range expectedKeys { + if val, ok := tagMap[key.Key]; ok { + labelValues = append(labelValues, metricdata.NewLabelValue(val)) + } else { + labelValues = append(labelValues, metricdata.LabelValue{}) + } + } + return labelValues +} + +func rowToTimeseries(v *viewInternal, row *Row, now time.Time, startTime time.Time) *metricdata.TimeSeries { + return &metricdata.TimeSeries{ + Points: []metricdata.Point{row.Data.toPoint(v.metricDescriptor.Type, now)}, + LabelValues: toLabelValues(row, v.metricDescriptor.LabelKeys), + StartTime: startTime, + } +} + +func viewToMetric(v *viewInternal, now time.Time, startTime time.Time) *metricdata.Metric { + if v.metricDescriptor.Type == metricdata.TypeGaugeInt64 || + v.metricDescriptor.Type == metricdata.TypeGaugeFloat64 { + startTime = time.Time{} + } + + rows := v.collectedRows() + if len(rows) == 0 { + return nil + } + + ts := []*metricdata.TimeSeries{} + for _, row := range rows { + ts = append(ts, rowToTimeseries(v, row, now, startTime)) + } + + m := &metricdata.Metric{ + Descriptor: *v.metricDescriptor, + TimeSeries: ts, + } + return m +} diff --git a/vendor/go.opencensus.io/stats/view/worker.go b/vendor/go.opencensus.io/stats/view/worker.go new file mode 100644 index 00000000..2f3c018a --- /dev/null +++ b/vendor/go.opencensus.io/stats/view/worker.go @@ -0,0 +1,281 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package view + +import ( + "fmt" + "sync" + "time" + + "go.opencensus.io/metric/metricdata" + "go.opencensus.io/metric/metricproducer" + "go.opencensus.io/stats" + "go.opencensus.io/stats/internal" + "go.opencensus.io/tag" +) + +func init() { + defaultWorker = newWorker() + go defaultWorker.start() + internal.DefaultRecorder = record +} + +type measureRef struct { + measure string + views map[*viewInternal]struct{} +} + +type worker struct { + measures map[string]*measureRef + views map[string]*viewInternal + startTimes map[*viewInternal]time.Time + + timer *time.Ticker + c chan command + quit, done chan bool + mu sync.RWMutex +} + +var defaultWorker *worker + +var defaultReportingDuration = 10 * time.Second + +// Find returns a registered view associated with this name. +// If no registered view is found, nil is returned. +func Find(name string) (v *View) { + req := &getViewByNameReq{ + name: name, + c: make(chan *getViewByNameResp), + } + defaultWorker.c <- req + resp := <-req.c + return resp.v +} + +// Register begins collecting data for the given views. +// Once a view is registered, it reports data to the registered exporters. +func Register(views ...*View) error { + req := ®isterViewReq{ + views: views, + err: make(chan error), + } + defaultWorker.c <- req + return <-req.err +} + +// Unregister the given views. Data will not longer be exported for these views +// after Unregister returns. +// It is not necessary to unregister from views you expect to collect for the +// duration of your program execution. +func Unregister(views ...*View) { + names := make([]string, len(views)) + for i := range views { + names[i] = views[i].Name + } + req := &unregisterFromViewReq{ + views: names, + done: make(chan struct{}), + } + defaultWorker.c <- req + <-req.done +} + +// RetrieveData gets a snapshot of the data collected for the the view registered +// with the given name. It is intended for testing only. +func RetrieveData(viewName string) ([]*Row, error) { + req := &retrieveDataReq{ + now: time.Now(), + v: viewName, + c: make(chan *retrieveDataResp), + } + defaultWorker.c <- req + resp := <-req.c + return resp.rows, resp.err +} + +func record(tags *tag.Map, ms interface{}, attachments map[string]interface{}) { + req := &recordReq{ + tm: tags, + ms: ms.([]stats.Measurement), + attachments: attachments, + t: time.Now(), + } + defaultWorker.c <- req +} + +// SetReportingPeriod sets the interval between reporting aggregated views in +// the program. If duration is less than or equal to zero, it enables the +// default behavior. +// +// Note: each exporter makes different promises about what the lowest supported +// duration is. For example, the Stackdriver exporter recommends a value no +// lower than 1 minute. Consult each exporter per your needs. +func SetReportingPeriod(d time.Duration) { + // TODO(acetechnologist): ensure that the duration d is more than a certain + // value. e.g. 1s + req := &setReportingPeriodReq{ + d: d, + c: make(chan bool), + } + defaultWorker.c <- req + <-req.c // don't return until the timer is set to the new duration. +} + +func newWorker() *worker { + return &worker{ + measures: make(map[string]*measureRef), + views: make(map[string]*viewInternal), + startTimes: make(map[*viewInternal]time.Time), + timer: time.NewTicker(defaultReportingDuration), + c: make(chan command, 1024), + quit: make(chan bool), + done: make(chan bool), + } +} + +func (w *worker) start() { + prodMgr := metricproducer.GlobalManager() + prodMgr.AddProducer(w) + + for { + select { + case cmd := <-w.c: + cmd.handleCommand(w) + case <-w.timer.C: + w.reportUsage(time.Now()) + case <-w.quit: + w.timer.Stop() + close(w.c) + w.done <- true + return + } + } +} + +func (w *worker) stop() { + prodMgr := metricproducer.GlobalManager() + prodMgr.DeleteProducer(w) + + w.quit <- true + <-w.done +} + +func (w *worker) getMeasureRef(name string) *measureRef { + if mr, ok := w.measures[name]; ok { + return mr + } + mr := &measureRef{ + measure: name, + views: make(map[*viewInternal]struct{}), + } + w.measures[name] = mr + return mr +} + +func (w *worker) tryRegisterView(v *View) (*viewInternal, error) { + w.mu.Lock() + defer w.mu.Unlock() + vi, err := newViewInternal(v) + if err != nil { + return nil, err + } + if x, ok := w.views[vi.view.Name]; ok { + if !x.view.same(vi.view) { + return nil, fmt.Errorf("cannot register view %q; a different view with the same name is already registered", v.Name) + } + + // the view is already registered so there is nothing to do and the + // command is considered successful. + return x, nil + } + w.views[vi.view.Name] = vi + ref := w.getMeasureRef(vi.view.Measure.Name()) + ref.views[vi] = struct{}{} + return vi, nil +} + +func (w *worker) unregisterView(viewName string) { + w.mu.Lock() + defer w.mu.Unlock() + delete(w.views, viewName) +} + +func (w *worker) reportView(v *viewInternal, now time.Time) { + if !v.isSubscribed() { + return + } + rows := v.collectedRows() + _, ok := w.startTimes[v] + if !ok { + w.startTimes[v] = now + } + viewData := &Data{ + View: v.view, + Start: w.startTimes[v], + End: time.Now(), + Rows: rows, + } + exportersMu.Lock() + for e := range exporters { + e.ExportView(viewData) + } + exportersMu.Unlock() +} + +func (w *worker) reportUsage(now time.Time) { + w.mu.Lock() + defer w.mu.Unlock() + for _, v := range w.views { + w.reportView(v, now) + } +} + +func (w *worker) toMetric(v *viewInternal, now time.Time) *metricdata.Metric { + if !v.isSubscribed() { + return nil + } + + _, ok := w.startTimes[v] + if !ok { + w.startTimes[v] = now + } + + var startTime time.Time + if v.metricDescriptor.Type == metricdata.TypeGaugeInt64 || + v.metricDescriptor.Type == metricdata.TypeGaugeFloat64 { + startTime = time.Time{} + } else { + startTime = w.startTimes[v] + } + + return viewToMetric(v, now, startTime) +} + +// Read reads all view data and returns them as metrics. +// It is typically invoked by metric reader to export stats in metric format. +func (w *worker) Read() []*metricdata.Metric { + w.mu.Lock() + defer w.mu.Unlock() + now := time.Now() + metrics := make([]*metricdata.Metric, 0, len(w.views)) + for _, v := range w.views { + metric := w.toMetric(v, now) + if metric != nil { + metrics = append(metrics, metric) + } + } + return metrics +} diff --git a/vendor/go.opencensus.io/stats/view/worker_commands.go b/vendor/go.opencensus.io/stats/view/worker_commands.go new file mode 100644 index 00000000..0267e179 --- /dev/null +++ b/vendor/go.opencensus.io/stats/view/worker_commands.go @@ -0,0 +1,186 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package view + +import ( + "errors" + "fmt" + "strings" + "time" + + "go.opencensus.io/stats" + "go.opencensus.io/stats/internal" + "go.opencensus.io/tag" +) + +type command interface { + handleCommand(w *worker) +} + +// getViewByNameReq is the command to get a view given its name. +type getViewByNameReq struct { + name string + c chan *getViewByNameResp +} + +type getViewByNameResp struct { + v *View +} + +func (cmd *getViewByNameReq) handleCommand(w *worker) { + v := w.views[cmd.name] + if v == nil { + cmd.c <- &getViewByNameResp{nil} + return + } + cmd.c <- &getViewByNameResp{v.view} +} + +// registerViewReq is the command to register a view. +type registerViewReq struct { + views []*View + err chan error +} + +func (cmd *registerViewReq) handleCommand(w *worker) { + for _, v := range cmd.views { + if err := v.canonicalize(); err != nil { + cmd.err <- err + return + } + } + var errstr []string + for _, view := range cmd.views { + vi, err := w.tryRegisterView(view) + if err != nil { + errstr = append(errstr, fmt.Sprintf("%s: %v", view.Name, err)) + continue + } + internal.SubscriptionReporter(view.Measure.Name()) + vi.subscribe() + } + if len(errstr) > 0 { + cmd.err <- errors.New(strings.Join(errstr, "\n")) + } else { + cmd.err <- nil + } +} + +// unregisterFromViewReq is the command to unregister to a view. Has no +// impact on the data collection for client that are pulling data from the +// library. +type unregisterFromViewReq struct { + views []string + done chan struct{} +} + +func (cmd *unregisterFromViewReq) handleCommand(w *worker) { + for _, name := range cmd.views { + vi, ok := w.views[name] + if !ok { + continue + } + + // Report pending data for this view before removing it. + w.reportView(vi, time.Now()) + + vi.unsubscribe() + if !vi.isSubscribed() { + // this was the last subscription and view is not collecting anymore. + // The collected data can be cleared. + vi.clearRows() + } + w.unregisterView(name) + } + cmd.done <- struct{}{} +} + +// retrieveDataReq is the command to retrieve data for a view. +type retrieveDataReq struct { + now time.Time + v string + c chan *retrieveDataResp +} + +type retrieveDataResp struct { + rows []*Row + err error +} + +func (cmd *retrieveDataReq) handleCommand(w *worker) { + w.mu.Lock() + defer w.mu.Unlock() + vi, ok := w.views[cmd.v] + if !ok { + cmd.c <- &retrieveDataResp{ + nil, + fmt.Errorf("cannot retrieve data; view %q is not registered", cmd.v), + } + return + } + + if !vi.isSubscribed() { + cmd.c <- &retrieveDataResp{ + nil, + fmt.Errorf("cannot retrieve data; view %q has no subscriptions or collection is not forcibly started", cmd.v), + } + return + } + cmd.c <- &retrieveDataResp{ + vi.collectedRows(), + nil, + } +} + +// recordReq is the command to record data related to multiple measures +// at once. +type recordReq struct { + tm *tag.Map + ms []stats.Measurement + attachments map[string]interface{} + t time.Time +} + +func (cmd *recordReq) handleCommand(w *worker) { + w.mu.Lock() + defer w.mu.Unlock() + for _, m := range cmd.ms { + if (m == stats.Measurement{}) { // not registered + continue + } + ref := w.getMeasureRef(m.Measure().Name()) + for v := range ref.views { + v.addSample(cmd.tm, m.Value(), cmd.attachments, time.Now()) + } + } +} + +// setReportingPeriodReq is the command to modify the duration between +// reporting the collected data to the registered clients. +type setReportingPeriodReq struct { + d time.Duration + c chan bool +} + +func (cmd *setReportingPeriodReq) handleCommand(w *worker) { + w.timer.Stop() + if cmd.d <= 0 { + w.timer = time.NewTicker(defaultReportingDuration) + } else { + w.timer = time.NewTicker(cmd.d) + } + cmd.c <- true +} diff --git a/vendor/go.opencensus.io/tag/context.go b/vendor/go.opencensus.io/tag/context.go new file mode 100644 index 00000000..b27d1b26 --- /dev/null +++ b/vendor/go.opencensus.io/tag/context.go @@ -0,0 +1,43 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package tag + +import ( + "context" +) + +// FromContext returns the tag map stored in the context. +func FromContext(ctx context.Context) *Map { + // The returned tag map shouldn't be mutated. + ts := ctx.Value(mapCtxKey) + if ts == nil { + return nil + } + return ts.(*Map) +} + +// NewContext creates a new context with the given tag map. +// To propagate a tag map to downstream methods and downstream RPCs, add a tag map +// to the current context. NewContext will return a copy of the current context, +// and put the tag map into the returned one. +// If there is already a tag map in the current context, it will be replaced with m. +func NewContext(ctx context.Context, m *Map) context.Context { + return context.WithValue(ctx, mapCtxKey, m) +} + +type ctxKey struct{} + +var mapCtxKey = ctxKey{} diff --git a/vendor/go.opencensus.io/tag/doc.go b/vendor/go.opencensus.io/tag/doc.go new file mode 100644 index 00000000..da16b74e --- /dev/null +++ b/vendor/go.opencensus.io/tag/doc.go @@ -0,0 +1,26 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/* +Package tag contains OpenCensus tags. + +Tags are key-value pairs. Tags provide additional cardinality to +the OpenCensus instrumentation data. + +Tags can be propagated on the wire and in the same +process via context.Context. Encode and Decode should be +used to represent tags into their binary propagation form. +*/ +package tag // import "go.opencensus.io/tag" diff --git a/vendor/go.opencensus.io/tag/key.go b/vendor/go.opencensus.io/tag/key.go new file mode 100644 index 00000000..ebbed950 --- /dev/null +++ b/vendor/go.opencensus.io/tag/key.go @@ -0,0 +1,35 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package tag + +// Key represents a tag key. +type Key struct { + name string +} + +// NewKey creates or retrieves a string key identified by name. +// Calling NewKey consequently with the same name returns the same key. +func NewKey(name string) (Key, error) { + if !checkKeyName(name) { + return Key{}, errInvalidKeyName + } + return Key{name: name}, nil +} + +// Name returns the name of the key. +func (k Key) Name() string { + return k.name +} diff --git a/vendor/go.opencensus.io/tag/map.go b/vendor/go.opencensus.io/tag/map.go new file mode 100644 index 00000000..0272ef85 --- /dev/null +++ b/vendor/go.opencensus.io/tag/map.go @@ -0,0 +1,229 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package tag + +import ( + "bytes" + "context" + "fmt" + "sort" +) + +// Tag is a key value pair that can be propagated on wire. +type Tag struct { + Key Key + Value string +} + +type tagContent struct { + value string + m metadatas +} + +// Map is a map of tags. Use New to create a context containing +// a new Map. +type Map struct { + m map[Key]tagContent +} + +// Value returns the value for the key if a value for the key exists. +func (m *Map) Value(k Key) (string, bool) { + if m == nil { + return "", false + } + v, ok := m.m[k] + return v.value, ok +} + +func (m *Map) String() string { + if m == nil { + return "nil" + } + keys := make([]Key, 0, len(m.m)) + for k := range m.m { + keys = append(keys, k) + } + sort.Slice(keys, func(i, j int) bool { return keys[i].Name() < keys[j].Name() }) + + var buffer bytes.Buffer + buffer.WriteString("{ ") + for _, k := range keys { + buffer.WriteString(fmt.Sprintf("{%v %v}", k.name, m.m[k])) + } + buffer.WriteString(" }") + return buffer.String() +} + +func (m *Map) insert(k Key, v string, md metadatas) { + if _, ok := m.m[k]; ok { + return + } + m.m[k] = tagContent{value: v, m: md} +} + +func (m *Map) update(k Key, v string, md metadatas) { + if _, ok := m.m[k]; ok { + m.m[k] = tagContent{value: v, m: md} + } +} + +func (m *Map) upsert(k Key, v string, md metadatas) { + m.m[k] = tagContent{value: v, m: md} +} + +func (m *Map) delete(k Key) { + delete(m.m, k) +} + +func newMap() *Map { + return &Map{m: make(map[Key]tagContent)} +} + +// Mutator modifies a tag map. +type Mutator interface { + Mutate(t *Map) (*Map, error) +} + +// Insert returns a mutator that inserts a +// value associated with k. If k already exists in the tag map, +// mutator doesn't update the value. +// Metadata applies metadata to the tag. It is optional. +// Metadatas are applied in the order in which it is provided. +// If more than one metadata updates the same attribute then +// the update from the last metadata prevails. +func Insert(k Key, v string, mds ...Metadata) Mutator { + return &mutator{ + fn: func(m *Map) (*Map, error) { + if !checkValue(v) { + return nil, errInvalidValue + } + m.insert(k, v, createMetadatas(mds...)) + return m, nil + }, + } +} + +// Update returns a mutator that updates the +// value of the tag associated with k with v. If k doesn't +// exists in the tag map, the mutator doesn't insert the value. +// Metadata applies metadata to the tag. It is optional. +// Metadatas are applied in the order in which it is provided. +// If more than one metadata updates the same attribute then +// the update from the last metadata prevails. +func Update(k Key, v string, mds ...Metadata) Mutator { + return &mutator{ + fn: func(m *Map) (*Map, error) { + if !checkValue(v) { + return nil, errInvalidValue + } + m.update(k, v, createMetadatas(mds...)) + return m, nil + }, + } +} + +// Upsert returns a mutator that upserts the +// value of the tag associated with k with v. It inserts the +// value if k doesn't exist already. It mutates the value +// if k already exists. +// Metadata applies metadata to the tag. It is optional. +// Metadatas are applied in the order in which it is provided. +// If more than one metadata updates the same attribute then +// the update from the last metadata prevails. +func Upsert(k Key, v string, mds ...Metadata) Mutator { + return &mutator{ + fn: func(m *Map) (*Map, error) { + if !checkValue(v) { + return nil, errInvalidValue + } + m.upsert(k, v, createMetadatas(mds...)) + return m, nil + }, + } +} + +func createMetadatas(mds ...Metadata) metadatas { + var metas metadatas + if len(mds) > 0 { + for _, md := range mds { + if md != nil { + md(&metas) + } + } + } else { + WithTTL(TTLUnlimitedPropagation)(&metas) + } + return metas + +} + +// Delete returns a mutator that deletes +// the value associated with k. +func Delete(k Key) Mutator { + return &mutator{ + fn: func(m *Map) (*Map, error) { + m.delete(k) + return m, nil + }, + } +} + +// New returns a new context that contains a tag map +// originated from the incoming context and modified +// with the provided mutators. +func New(ctx context.Context, mutator ...Mutator) (context.Context, error) { + m := newMap() + orig := FromContext(ctx) + if orig != nil { + for k, v := range orig.m { + if !checkKeyName(k.Name()) { + return ctx, fmt.Errorf("key:%q: %v", k, errInvalidKeyName) + } + if !checkValue(v.value) { + return ctx, fmt.Errorf("key:%q value:%q: %v", k.Name(), v, errInvalidValue) + } + m.insert(k, v.value, v.m) + } + } + var err error + for _, mod := range mutator { + m, err = mod.Mutate(m) + if err != nil { + return ctx, err + } + } + return NewContext(ctx, m), nil +} + +// Do is similar to pprof.Do: a convenience for installing the tags +// from the context as Go profiler labels. This allows you to +// correlated runtime profiling with stats. +// +// It converts the key/values from the given map to Go profiler labels +// and calls pprof.Do. +// +// Do is going to do nothing if your Go version is below 1.9. +func Do(ctx context.Context, f func(ctx context.Context)) { + do(ctx, f) +} + +type mutator struct { + fn func(t *Map) (*Map, error) +} + +func (m *mutator) Mutate(t *Map) (*Map, error) { + return m.fn(t) +} diff --git a/vendor/go.opencensus.io/tag/map_codec.go b/vendor/go.opencensus.io/tag/map_codec.go new file mode 100644 index 00000000..f8b58276 --- /dev/null +++ b/vendor/go.opencensus.io/tag/map_codec.go @@ -0,0 +1,239 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package tag + +import ( + "encoding/binary" + "fmt" +) + +// KeyType defines the types of keys allowed. Currently only keyTypeString is +// supported. +type keyType byte + +const ( + keyTypeString keyType = iota + keyTypeInt64 + keyTypeTrue + keyTypeFalse + + tagsVersionID = byte(0) +) + +type encoderGRPC struct { + buf []byte + writeIdx, readIdx int +} + +// writeKeyString writes the fieldID '0' followed by the key string and value +// string. +func (eg *encoderGRPC) writeTagString(k, v string) { + eg.writeByte(byte(keyTypeString)) + eg.writeStringWithVarintLen(k) + eg.writeStringWithVarintLen(v) +} + +func (eg *encoderGRPC) writeTagUint64(k string, i uint64) { + eg.writeByte(byte(keyTypeInt64)) + eg.writeStringWithVarintLen(k) + eg.writeUint64(i) +} + +func (eg *encoderGRPC) writeTagTrue(k string) { + eg.writeByte(byte(keyTypeTrue)) + eg.writeStringWithVarintLen(k) +} + +func (eg *encoderGRPC) writeTagFalse(k string) { + eg.writeByte(byte(keyTypeFalse)) + eg.writeStringWithVarintLen(k) +} + +func (eg *encoderGRPC) writeBytesWithVarintLen(bytes []byte) { + length := len(bytes) + + eg.growIfRequired(binary.MaxVarintLen64 + length) + eg.writeIdx += binary.PutUvarint(eg.buf[eg.writeIdx:], uint64(length)) + copy(eg.buf[eg.writeIdx:], bytes) + eg.writeIdx += length +} + +func (eg *encoderGRPC) writeStringWithVarintLen(s string) { + length := len(s) + + eg.growIfRequired(binary.MaxVarintLen64 + length) + eg.writeIdx += binary.PutUvarint(eg.buf[eg.writeIdx:], uint64(length)) + copy(eg.buf[eg.writeIdx:], s) + eg.writeIdx += length +} + +func (eg *encoderGRPC) writeByte(v byte) { + eg.growIfRequired(1) + eg.buf[eg.writeIdx] = v + eg.writeIdx++ +} + +func (eg *encoderGRPC) writeUint32(i uint32) { + eg.growIfRequired(4) + binary.LittleEndian.PutUint32(eg.buf[eg.writeIdx:], i) + eg.writeIdx += 4 +} + +func (eg *encoderGRPC) writeUint64(i uint64) { + eg.growIfRequired(8) + binary.LittleEndian.PutUint64(eg.buf[eg.writeIdx:], i) + eg.writeIdx += 8 +} + +func (eg *encoderGRPC) readByte() byte { + b := eg.buf[eg.readIdx] + eg.readIdx++ + return b +} + +func (eg *encoderGRPC) readUint32() uint32 { + i := binary.LittleEndian.Uint32(eg.buf[eg.readIdx:]) + eg.readIdx += 4 + return i +} + +func (eg *encoderGRPC) readUint64() uint64 { + i := binary.LittleEndian.Uint64(eg.buf[eg.readIdx:]) + eg.readIdx += 8 + return i +} + +func (eg *encoderGRPC) readBytesWithVarintLen() ([]byte, error) { + if eg.readEnded() { + return nil, fmt.Errorf("unexpected end while readBytesWithVarintLen '%x' starting at idx '%v'", eg.buf, eg.readIdx) + } + length, valueStart := binary.Uvarint(eg.buf[eg.readIdx:]) + if valueStart <= 0 { + return nil, fmt.Errorf("unexpected end while readBytesWithVarintLen '%x' starting at idx '%v'", eg.buf, eg.readIdx) + } + + valueStart += eg.readIdx + valueEnd := valueStart + int(length) + if valueEnd > len(eg.buf) { + return nil, fmt.Errorf("malformed encoding: length:%v, upper:%v, maxLength:%v", length, valueEnd, len(eg.buf)) + } + + eg.readIdx = valueEnd + return eg.buf[valueStart:valueEnd], nil +} + +func (eg *encoderGRPC) readStringWithVarintLen() (string, error) { + bytes, err := eg.readBytesWithVarintLen() + if err != nil { + return "", err + } + return string(bytes), nil +} + +func (eg *encoderGRPC) growIfRequired(expected int) { + if len(eg.buf)-eg.writeIdx < expected { + tmp := make([]byte, 2*(len(eg.buf)+1)+expected) + copy(tmp, eg.buf) + eg.buf = tmp + } +} + +func (eg *encoderGRPC) readEnded() bool { + return eg.readIdx >= len(eg.buf) +} + +func (eg *encoderGRPC) bytes() []byte { + return eg.buf[:eg.writeIdx] +} + +// Encode encodes the tag map into a []byte. It is useful to propagate +// the tag maps on wire in binary format. +func Encode(m *Map) []byte { + if m == nil { + return nil + } + eg := &encoderGRPC{ + buf: make([]byte, len(m.m)), + } + eg.writeByte(byte(tagsVersionID)) + for k, v := range m.m { + if v.m.ttl.ttl == valueTTLUnlimitedPropagation { + eg.writeByte(byte(keyTypeString)) + eg.writeStringWithVarintLen(k.name) + eg.writeBytesWithVarintLen([]byte(v.value)) + } + } + return eg.bytes() +} + +// Decode decodes the given []byte into a tag map. +func Decode(bytes []byte) (*Map, error) { + ts := newMap() + err := DecodeEach(bytes, ts.upsert) + if err != nil { + // no partial failures + return nil, err + } + return ts, nil +} + +// DecodeEach decodes the given serialized tag map, calling handler for each +// tag key and value decoded. +func DecodeEach(bytes []byte, fn func(key Key, val string, md metadatas)) error { + eg := &encoderGRPC{ + buf: bytes, + } + if len(eg.buf) == 0 { + return nil + } + + version := eg.readByte() + if version > tagsVersionID { + return fmt.Errorf("cannot decode: unsupported version: %q; supports only up to: %q", version, tagsVersionID) + } + + for !eg.readEnded() { + typ := keyType(eg.readByte()) + + if typ != keyTypeString { + return fmt.Errorf("cannot decode: invalid key type: %q", typ) + } + + k, err := eg.readBytesWithVarintLen() + if err != nil { + return err + } + + v, err := eg.readBytesWithVarintLen() + if err != nil { + return err + } + + key, err := NewKey(string(k)) + if err != nil { + return err + } + val := string(v) + if !checkValue(val) { + return errInvalidValue + } + fn(key, val, createMetadatas(WithTTL(TTLUnlimitedPropagation))) + if err != nil { + return err + } + } + return nil +} diff --git a/vendor/go.opencensus.io/tag/metadata.go b/vendor/go.opencensus.io/tag/metadata.go new file mode 100644 index 00000000..6571a583 --- /dev/null +++ b/vendor/go.opencensus.io/tag/metadata.go @@ -0,0 +1,52 @@ +// Copyright 2019, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package tag + +const ( + // valueTTLNoPropagation prevents tag from propagating. + valueTTLNoPropagation = 0 + + // valueTTLUnlimitedPropagation allows tag to propagate without any limits on number of hops. + valueTTLUnlimitedPropagation = -1 +) + +// TTL is metadata that specifies number of hops a tag can propagate. +// Details about TTL metadata is specified at https://github.com/census-instrumentation/opencensus-specs/blob/master/tags/TagMap.md#tagmetadata +type TTL struct { + ttl int +} + +var ( + // TTLUnlimitedPropagation is TTL metadata that allows tag to propagate without any limits on number of hops. + TTLUnlimitedPropagation = TTL{ttl: valueTTLUnlimitedPropagation} + + // TTLNoPropagation is TTL metadata that prevents tag from propagating. + TTLNoPropagation = TTL{ttl: valueTTLNoPropagation} +) + +type metadatas struct { + ttl TTL +} + +// Metadata applies metadatas specified by the function. +type Metadata func(*metadatas) + +// WithTTL applies metadata with provided ttl. +func WithTTL(ttl TTL) Metadata { + return func(m *metadatas) { + m.ttl = ttl + } +} diff --git a/vendor/go.opencensus.io/tag/profile_19.go b/vendor/go.opencensus.io/tag/profile_19.go new file mode 100644 index 00000000..b34d95e3 --- /dev/null +++ b/vendor/go.opencensus.io/tag/profile_19.go @@ -0,0 +1,31 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build go1.9 + +package tag + +import ( + "context" + "runtime/pprof" +) + +func do(ctx context.Context, f func(ctx context.Context)) { + m := FromContext(ctx) + keyvals := make([]string, 0, 2*len(m.m)) + for k, v := range m.m { + keyvals = append(keyvals, k.Name(), v.value) + } + pprof.Do(ctx, pprof.Labels(keyvals...), f) +} diff --git a/vendor/go.opencensus.io/tag/profile_not19.go b/vendor/go.opencensus.io/tag/profile_not19.go new file mode 100644 index 00000000..83adbce5 --- /dev/null +++ b/vendor/go.opencensus.io/tag/profile_not19.go @@ -0,0 +1,23 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build !go1.9 + +package tag + +import "context" + +func do(ctx context.Context, f func(ctx context.Context)) { + f(ctx) +} diff --git a/vendor/go.opencensus.io/tag/validate.go b/vendor/go.opencensus.io/tag/validate.go new file mode 100644 index 00000000..0939fc67 --- /dev/null +++ b/vendor/go.opencensus.io/tag/validate.go @@ -0,0 +1,56 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package tag + +import "errors" + +const ( + maxKeyLength = 255 + + // valid are restricted to US-ASCII subset (range 0x20 (' ') to 0x7e ('~')). + validKeyValueMin = 32 + validKeyValueMax = 126 +) + +var ( + errInvalidKeyName = errors.New("invalid key name: only ASCII characters accepted; max length must be 255 characters") + errInvalidValue = errors.New("invalid value: only ASCII characters accepted; max length must be 255 characters") +) + +func checkKeyName(name string) bool { + if len(name) == 0 { + return false + } + if len(name) > maxKeyLength { + return false + } + return isASCII(name) +} + +func isASCII(s string) bool { + for _, c := range s { + if (c < validKeyValueMin) || (c > validKeyValueMax) { + return false + } + } + return true +} + +func checkValue(v string) bool { + if len(v) > maxKeyLength { + return false + } + return isASCII(v) +} diff --git a/vendor/go.opencensus.io/trace/basetypes.go b/vendor/go.opencensus.io/trace/basetypes.go new file mode 100644 index 00000000..0c54492a --- /dev/null +++ b/vendor/go.opencensus.io/trace/basetypes.go @@ -0,0 +1,119 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package trace + +import ( + "fmt" + "time" +) + +type ( + // TraceID is a 16-byte identifier for a set of spans. + TraceID [16]byte + + // SpanID is an 8-byte identifier for a single span. + SpanID [8]byte +) + +func (t TraceID) String() string { + return fmt.Sprintf("%02x", t[:]) +} + +func (s SpanID) String() string { + return fmt.Sprintf("%02x", s[:]) +} + +// Annotation represents a text annotation with a set of attributes and a timestamp. +type Annotation struct { + Time time.Time + Message string + Attributes map[string]interface{} +} + +// Attribute represents a key-value pair on a span, link or annotation. +// Construct with one of: BoolAttribute, Int64Attribute, or StringAttribute. +type Attribute struct { + key string + value interface{} +} + +// BoolAttribute returns a bool-valued attribute. +func BoolAttribute(key string, value bool) Attribute { + return Attribute{key: key, value: value} +} + +// Int64Attribute returns an int64-valued attribute. +func Int64Attribute(key string, value int64) Attribute { + return Attribute{key: key, value: value} +} + +// Float64Attribute returns a float64-valued attribute. +func Float64Attribute(key string, value float64) Attribute { + return Attribute{key: key, value: value} +} + +// StringAttribute returns a string-valued attribute. +func StringAttribute(key string, value string) Attribute { + return Attribute{key: key, value: value} +} + +// LinkType specifies the relationship between the span that had the link +// added, and the linked span. +type LinkType int32 + +// LinkType values. +const ( + LinkTypeUnspecified LinkType = iota // The relationship of the two spans is unknown. + LinkTypeChild // The linked span is a child of the current span. + LinkTypeParent // The linked span is the parent of the current span. +) + +// Link represents a reference from one span to another span. +type Link struct { + TraceID TraceID + SpanID SpanID + Type LinkType + // Attributes is a set of attributes on the link. + Attributes map[string]interface{} +} + +// MessageEventType specifies the type of message event. +type MessageEventType int32 + +// MessageEventType values. +const ( + MessageEventTypeUnspecified MessageEventType = iota // Unknown event type. + MessageEventTypeSent // Indicates a sent RPC message. + MessageEventTypeRecv // Indicates a received RPC message. +) + +// MessageEvent represents an event describing a message sent or received on the network. +type MessageEvent struct { + Time time.Time + EventType MessageEventType + MessageID int64 + UncompressedByteSize int64 + CompressedByteSize int64 +} + +// Status is the status of a Span. +type Status struct { + // Code is a status code. Zero indicates success. + // + // If Code will be propagated to Google APIs, it ideally should be a value from + // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto . + Code int32 + Message string +} diff --git a/vendor/go.opencensus.io/trace/config.go b/vendor/go.opencensus.io/trace/config.go new file mode 100644 index 00000000..775f8274 --- /dev/null +++ b/vendor/go.opencensus.io/trace/config.go @@ -0,0 +1,86 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package trace + +import ( + "sync" + + "go.opencensus.io/trace/internal" +) + +// Config represents the global tracing configuration. +type Config struct { + // DefaultSampler is the default sampler used when creating new spans. + DefaultSampler Sampler + + // IDGenerator is for internal use only. + IDGenerator internal.IDGenerator + + // MaxAnnotationEventsPerSpan is max number of annotation events per span + MaxAnnotationEventsPerSpan int + + // MaxMessageEventsPerSpan is max number of message events per span + MaxMessageEventsPerSpan int + + // MaxAnnotationEventsPerSpan is max number of attributes per span + MaxAttributesPerSpan int + + // MaxLinksPerSpan is max number of links per span + MaxLinksPerSpan int +} + +var configWriteMu sync.Mutex + +const ( + // DefaultMaxAnnotationEventsPerSpan is default max number of annotation events per span + DefaultMaxAnnotationEventsPerSpan = 32 + + // DefaultMaxMessageEventsPerSpan is default max number of message events per span + DefaultMaxMessageEventsPerSpan = 128 + + // DefaultMaxAttributesPerSpan is default max number of attributes per span + DefaultMaxAttributesPerSpan = 32 + + // DefaultMaxLinksPerSpan is default max number of links per span + DefaultMaxLinksPerSpan = 32 +) + +// ApplyConfig applies changes to the global tracing configuration. +// +// Fields not provided in the given config are going to be preserved. +func ApplyConfig(cfg Config) { + configWriteMu.Lock() + defer configWriteMu.Unlock() + c := *config.Load().(*Config) + if cfg.DefaultSampler != nil { + c.DefaultSampler = cfg.DefaultSampler + } + if cfg.IDGenerator != nil { + c.IDGenerator = cfg.IDGenerator + } + if cfg.MaxAnnotationEventsPerSpan > 0 { + c.MaxAnnotationEventsPerSpan = cfg.MaxAnnotationEventsPerSpan + } + if cfg.MaxMessageEventsPerSpan > 0 { + c.MaxMessageEventsPerSpan = cfg.MaxMessageEventsPerSpan + } + if cfg.MaxAttributesPerSpan > 0 { + c.MaxAttributesPerSpan = cfg.MaxAttributesPerSpan + } + if cfg.MaxLinksPerSpan > 0 { + c.MaxLinksPerSpan = cfg.MaxLinksPerSpan + } + config.Store(&c) +} diff --git a/vendor/go.opencensus.io/trace/doc.go b/vendor/go.opencensus.io/trace/doc.go new file mode 100644 index 00000000..04b1ee4f --- /dev/null +++ b/vendor/go.opencensus.io/trace/doc.go @@ -0,0 +1,53 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/* +Package trace contains support for OpenCensus distributed tracing. + +The following assumes a basic familiarity with OpenCensus concepts. +See http://opencensus.io + + +Exporting Traces + +To export collected tracing data, register at least one exporter. You can use +one of the provided exporters or write your own. + + trace.RegisterExporter(exporter) + +By default, traces will be sampled relatively rarely. To change the sampling +frequency for your entire program, call ApplyConfig. Use a ProbabilitySampler +to sample a subset of traces, or use AlwaysSample to collect a trace on every run: + + trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()}) + +Be careful about using trace.AlwaysSample in a production application with +significant traffic: a new trace will be started and exported for every request. + +Adding Spans to a Trace + +A trace consists of a tree of spans. In Go, the current span is carried in a +context.Context. + +It is common to want to capture all the activity of a function call in a span. For +this to work, the function must take a context.Context as a parameter. Add these two +lines to the top of the function: + + ctx, span := trace.StartSpan(ctx, "example.com/Run") + defer span.End() + +StartSpan will create a new top-level span if the context +doesn't contain another span, otherwise it will create a child span. +*/ +package trace // import "go.opencensus.io/trace" diff --git a/vendor/go.opencensus.io/trace/evictedqueue.go b/vendor/go.opencensus.io/trace/evictedqueue.go new file mode 100644 index 00000000..ffc264f2 --- /dev/null +++ b/vendor/go.opencensus.io/trace/evictedqueue.go @@ -0,0 +1,38 @@ +// Copyright 2019, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package trace + +type evictedQueue struct { + queue []interface{} + capacity int + droppedCount int +} + +func newEvictedQueue(capacity int) *evictedQueue { + eq := &evictedQueue{ + capacity: capacity, + queue: make([]interface{}, 0), + } + + return eq +} + +func (eq *evictedQueue) add(value interface{}) { + if len(eq.queue) == eq.capacity { + eq.queue = eq.queue[1:] + eq.droppedCount++ + } + eq.queue = append(eq.queue, value) +} diff --git a/vendor/go.opencensus.io/trace/export.go b/vendor/go.opencensus.io/trace/export.go new file mode 100644 index 00000000..e0d9a4b9 --- /dev/null +++ b/vendor/go.opencensus.io/trace/export.go @@ -0,0 +1,97 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package trace + +import ( + "sync" + "sync/atomic" + "time" +) + +// Exporter is a type for functions that receive sampled trace spans. +// +// The ExportSpan method should be safe for concurrent use and should return +// quickly; if an Exporter takes a significant amount of time to process a +// SpanData, that work should be done on another goroutine. +// +// The SpanData should not be modified, but a pointer to it can be kept. +type Exporter interface { + ExportSpan(s *SpanData) +} + +type exportersMap map[Exporter]struct{} + +var ( + exporterMu sync.Mutex + exporters atomic.Value +) + +// RegisterExporter adds to the list of Exporters that will receive sampled +// trace spans. +// +// Binaries can register exporters, libraries shouldn't register exporters. +func RegisterExporter(e Exporter) { + exporterMu.Lock() + new := make(exportersMap) + if old, ok := exporters.Load().(exportersMap); ok { + for k, v := range old { + new[k] = v + } + } + new[e] = struct{}{} + exporters.Store(new) + exporterMu.Unlock() +} + +// UnregisterExporter removes from the list of Exporters the Exporter that was +// registered with the given name. +func UnregisterExporter(e Exporter) { + exporterMu.Lock() + new := make(exportersMap) + if old, ok := exporters.Load().(exportersMap); ok { + for k, v := range old { + new[k] = v + } + } + delete(new, e) + exporters.Store(new) + exporterMu.Unlock() +} + +// SpanData contains all the information collected by a Span. +type SpanData struct { + SpanContext + ParentSpanID SpanID + SpanKind int + Name string + StartTime time.Time + // The wall clock time of EndTime will be adjusted to always be offset + // from StartTime by the duration of the span. + EndTime time.Time + // The values of Attributes each have type string, bool, or int64. + Attributes map[string]interface{} + Annotations []Annotation + MessageEvents []MessageEvent + Status + Links []Link + HasRemoteParent bool + DroppedAttributeCount int + DroppedAnnotationCount int + DroppedMessageEventCount int + DroppedLinkCount int + + // ChildSpanCount holds the number of child span created for this span. + ChildSpanCount int +} diff --git a/vendor/go.opencensus.io/trace/internal/internal.go b/vendor/go.opencensus.io/trace/internal/internal.go new file mode 100644 index 00000000..7e808d8f --- /dev/null +++ b/vendor/go.opencensus.io/trace/internal/internal.go @@ -0,0 +1,22 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package internal provides trace internals. +package internal + +// IDGenerator allows custom generators for TraceId and SpanId. +type IDGenerator interface { + NewTraceID() [16]byte + NewSpanID() [8]byte +} diff --git a/vendor/go.opencensus.io/trace/lrumap.go b/vendor/go.opencensus.io/trace/lrumap.go new file mode 100644 index 00000000..3f80a336 --- /dev/null +++ b/vendor/go.opencensus.io/trace/lrumap.go @@ -0,0 +1,37 @@ +// Copyright 2019, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package trace + +import ( + "github.com/hashicorp/golang-lru/simplelru" +) + +type lruMap struct { + simpleLruMap *simplelru.LRU + droppedCount int +} + +func newLruMap(size int) *lruMap { + lm := &lruMap{} + lm.simpleLruMap, _ = simplelru.NewLRU(size, nil) + return lm +} + +func (lm *lruMap) add(key, value interface{}) { + evicted := lm.simpleLruMap.Add(key, value) + if evicted { + lm.droppedCount++ + } +} diff --git a/vendor/go.opencensus.io/trace/propagation/propagation.go b/vendor/go.opencensus.io/trace/propagation/propagation.go new file mode 100644 index 00000000..1eb190a9 --- /dev/null +++ b/vendor/go.opencensus.io/trace/propagation/propagation.go @@ -0,0 +1,108 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package propagation implements the binary trace context format. +package propagation // import "go.opencensus.io/trace/propagation" + +// TODO: link to external spec document. + +// BinaryFormat format: +// +// Binary value: +// version_id: 1 byte representing the version id. +// +// For version_id = 0: +// +// version_format: +// field_format: +// +// Fields: +// +// TraceId: (field_id = 0, len = 16, default = "0000000000000000") - 16-byte array representing the trace_id. +// SpanId: (field_id = 1, len = 8, default = "00000000") - 8-byte array representing the span_id. +// TraceOptions: (field_id = 2, len = 1, default = "0") - 1-byte array representing the trace_options. +// +// Fields MUST be encoded using the field id order (smaller to higher). +// +// Valid value example: +// +// {0, 0, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 1, 97, +// 98, 99, 100, 101, 102, 103, 104, 2, 1} +// +// version_id = 0; +// trace_id = {64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79} +// span_id = {97, 98, 99, 100, 101, 102, 103, 104}; +// trace_options = {1}; + +import ( + "net/http" + + "go.opencensus.io/trace" +) + +// Binary returns the binary format representation of a SpanContext. +// +// If sc is the zero value, Binary returns nil. +func Binary(sc trace.SpanContext) []byte { + if sc == (trace.SpanContext{}) { + return nil + } + var b [29]byte + copy(b[2:18], sc.TraceID[:]) + b[18] = 1 + copy(b[19:27], sc.SpanID[:]) + b[27] = 2 + b[28] = uint8(sc.TraceOptions) + return b[:] +} + +// FromBinary returns the SpanContext represented by b. +// +// If b has an unsupported version ID or contains no TraceID, FromBinary +// returns with ok==false. +func FromBinary(b []byte) (sc trace.SpanContext, ok bool) { + if len(b) == 0 || b[0] != 0 { + return trace.SpanContext{}, false + } + b = b[1:] + if len(b) >= 17 && b[0] == 0 { + copy(sc.TraceID[:], b[1:17]) + b = b[17:] + } else { + return trace.SpanContext{}, false + } + if len(b) >= 9 && b[0] == 1 { + copy(sc.SpanID[:], b[1:9]) + b = b[9:] + } + if len(b) >= 2 && b[0] == 2 { + sc.TraceOptions = trace.TraceOptions(b[1]) + } + return sc, true +} + +// HTTPFormat implementations propagate span contexts +// in HTTP requests. +// +// SpanContextFromRequest extracts a span context from incoming +// requests. +// +// SpanContextToRequest modifies the given request to include the given +// span context. +type HTTPFormat interface { + SpanContextFromRequest(req *http.Request) (sc trace.SpanContext, ok bool) + SpanContextToRequest(sc trace.SpanContext, req *http.Request) +} + +// TODO(jbd): Find a more representative but short name for HTTPFormat. diff --git a/vendor/go.opencensus.io/trace/sampling.go b/vendor/go.opencensus.io/trace/sampling.go new file mode 100644 index 00000000..71c10f9e --- /dev/null +++ b/vendor/go.opencensus.io/trace/sampling.go @@ -0,0 +1,75 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package trace + +import ( + "encoding/binary" +) + +const defaultSamplingProbability = 1e-4 + +// Sampler decides whether a trace should be sampled and exported. +type Sampler func(SamplingParameters) SamplingDecision + +// SamplingParameters contains the values passed to a Sampler. +type SamplingParameters struct { + ParentContext SpanContext + TraceID TraceID + SpanID SpanID + Name string + HasRemoteParent bool +} + +// SamplingDecision is the value returned by a Sampler. +type SamplingDecision struct { + Sample bool +} + +// ProbabilitySampler returns a Sampler that samples a given fraction of traces. +// +// It also samples spans whose parents are sampled. +func ProbabilitySampler(fraction float64) Sampler { + if !(fraction >= 0) { + fraction = 0 + } else if fraction >= 1 { + return AlwaysSample() + } + + traceIDUpperBound := uint64(fraction * (1 << 63)) + return Sampler(func(p SamplingParameters) SamplingDecision { + if p.ParentContext.IsSampled() { + return SamplingDecision{Sample: true} + } + x := binary.BigEndian.Uint64(p.TraceID[0:8]) >> 1 + return SamplingDecision{Sample: x < traceIDUpperBound} + }) +} + +// AlwaysSample returns a Sampler that samples every trace. +// Be careful about using this sampler in a production application with +// significant traffic: a new trace will be started and exported for every +// request. +func AlwaysSample() Sampler { + return func(p SamplingParameters) SamplingDecision { + return SamplingDecision{Sample: true} + } +} + +// NeverSample returns a Sampler that samples no traces. +func NeverSample() Sampler { + return func(p SamplingParameters) SamplingDecision { + return SamplingDecision{Sample: false} + } +} diff --git a/vendor/go.opencensus.io/trace/spanbucket.go b/vendor/go.opencensus.io/trace/spanbucket.go new file mode 100644 index 00000000..fbabad34 --- /dev/null +++ b/vendor/go.opencensus.io/trace/spanbucket.go @@ -0,0 +1,130 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package trace + +import ( + "time" +) + +// samplePeriod is the minimum time between accepting spans in a single bucket. +const samplePeriod = time.Second + +// defaultLatencies contains the default latency bucket bounds. +// TODO: consider defaults, make configurable +var defaultLatencies = [...]time.Duration{ + 10 * time.Microsecond, + 100 * time.Microsecond, + time.Millisecond, + 10 * time.Millisecond, + 100 * time.Millisecond, + time.Second, + 10 * time.Second, + time.Minute, +} + +// bucket is a container for a set of spans for a particular error code or latency range. +type bucket struct { + nextTime time.Time // next time we can accept a span + buffer []*SpanData // circular buffer of spans + nextIndex int // location next SpanData should be placed in buffer + overflow bool // whether the circular buffer has wrapped around +} + +func makeBucket(bufferSize int) bucket { + return bucket{ + buffer: make([]*SpanData, bufferSize), + } +} + +// add adds a span to the bucket, if nextTime has been reached. +func (b *bucket) add(s *SpanData) { + if s.EndTime.Before(b.nextTime) { + return + } + if len(b.buffer) == 0 { + return + } + b.nextTime = s.EndTime.Add(samplePeriod) + b.buffer[b.nextIndex] = s + b.nextIndex++ + if b.nextIndex == len(b.buffer) { + b.nextIndex = 0 + b.overflow = true + } +} + +// size returns the number of spans in the bucket. +func (b *bucket) size() int { + if b.overflow { + return len(b.buffer) + } + return b.nextIndex +} + +// span returns the ith span in the bucket. +func (b *bucket) span(i int) *SpanData { + if !b.overflow { + return b.buffer[i] + } + if i < len(b.buffer)-b.nextIndex { + return b.buffer[b.nextIndex+i] + } + return b.buffer[b.nextIndex+i-len(b.buffer)] +} + +// resize changes the size of the bucket to n, keeping up to n existing spans. +func (b *bucket) resize(n int) { + cur := b.size() + newBuffer := make([]*SpanData, n) + if cur < n { + for i := 0; i < cur; i++ { + newBuffer[i] = b.span(i) + } + b.buffer = newBuffer + b.nextIndex = cur + b.overflow = false + return + } + for i := 0; i < n; i++ { + newBuffer[i] = b.span(i + cur - n) + } + b.buffer = newBuffer + b.nextIndex = 0 + b.overflow = true +} + +// latencyBucket returns the appropriate bucket number for a given latency. +func latencyBucket(latency time.Duration) int { + i := 0 + for i < len(defaultLatencies) && latency >= defaultLatencies[i] { + i++ + } + return i +} + +// latencyBucketBounds returns the lower and upper bounds for a latency bucket +// number. +// +// The lower bound is inclusive, the upper bound is exclusive (except for the +// last bucket.) +func latencyBucketBounds(index int) (lower time.Duration, upper time.Duration) { + if index == 0 { + return 0, defaultLatencies[index] + } + if index == len(defaultLatencies) { + return defaultLatencies[index-1], 1<<63 - 1 + } + return defaultLatencies[index-1], defaultLatencies[index] +} diff --git a/vendor/go.opencensus.io/trace/spanstore.go b/vendor/go.opencensus.io/trace/spanstore.go new file mode 100644 index 00000000..c442d990 --- /dev/null +++ b/vendor/go.opencensus.io/trace/spanstore.go @@ -0,0 +1,306 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package trace + +import ( + "sync" + "time" + + "go.opencensus.io/internal" +) + +const ( + maxBucketSize = 100000 + defaultBucketSize = 10 +) + +var ( + ssmu sync.RWMutex // protects spanStores + spanStores = make(map[string]*spanStore) +) + +// This exists purely to avoid exposing internal methods used by z-Pages externally. +type internalOnly struct{} + +func init() { + //TODO(#412): remove + internal.Trace = &internalOnly{} +} + +// ReportActiveSpans returns the active spans for the given name. +func (i internalOnly) ReportActiveSpans(name string) []*SpanData { + s := spanStoreForName(name) + if s == nil { + return nil + } + var out []*SpanData + s.mu.Lock() + defer s.mu.Unlock() + for span := range s.active { + out = append(out, span.makeSpanData()) + } + return out +} + +// ReportSpansByError returns a sample of error spans. +// +// If code is nonzero, only spans with that status code are returned. +func (i internalOnly) ReportSpansByError(name string, code int32) []*SpanData { + s := spanStoreForName(name) + if s == nil { + return nil + } + var out []*SpanData + s.mu.Lock() + defer s.mu.Unlock() + if code != 0 { + if b, ok := s.errors[code]; ok { + for _, sd := range b.buffer { + if sd == nil { + break + } + out = append(out, sd) + } + } + } else { + for _, b := range s.errors { + for _, sd := range b.buffer { + if sd == nil { + break + } + out = append(out, sd) + } + } + } + return out +} + +// ConfigureBucketSizes sets the number of spans to keep per latency and error +// bucket for different span names. +func (i internalOnly) ConfigureBucketSizes(bcs []internal.BucketConfiguration) { + for _, bc := range bcs { + latencyBucketSize := bc.MaxRequestsSucceeded + if latencyBucketSize < 0 { + latencyBucketSize = 0 + } + if latencyBucketSize > maxBucketSize { + latencyBucketSize = maxBucketSize + } + errorBucketSize := bc.MaxRequestsErrors + if errorBucketSize < 0 { + errorBucketSize = 0 + } + if errorBucketSize > maxBucketSize { + errorBucketSize = maxBucketSize + } + spanStoreSetSize(bc.Name, latencyBucketSize, errorBucketSize) + } +} + +// ReportSpansPerMethod returns a summary of what spans are being stored for each span name. +func (i internalOnly) ReportSpansPerMethod() map[string]internal.PerMethodSummary { + out := make(map[string]internal.PerMethodSummary) + ssmu.RLock() + defer ssmu.RUnlock() + for name, s := range spanStores { + s.mu.Lock() + p := internal.PerMethodSummary{ + Active: len(s.active), + } + for code, b := range s.errors { + p.ErrorBuckets = append(p.ErrorBuckets, internal.ErrorBucketSummary{ + ErrorCode: code, + Size: b.size(), + }) + } + for i, b := range s.latency { + min, max := latencyBucketBounds(i) + p.LatencyBuckets = append(p.LatencyBuckets, internal.LatencyBucketSummary{ + MinLatency: min, + MaxLatency: max, + Size: b.size(), + }) + } + s.mu.Unlock() + out[name] = p + } + return out +} + +// ReportSpansByLatency returns a sample of successful spans. +// +// minLatency is the minimum latency of spans to be returned. +// maxLatency, if nonzero, is the maximum latency of spans to be returned. +func (i internalOnly) ReportSpansByLatency(name string, minLatency, maxLatency time.Duration) []*SpanData { + s := spanStoreForName(name) + if s == nil { + return nil + } + var out []*SpanData + s.mu.Lock() + defer s.mu.Unlock() + for i, b := range s.latency { + min, max := latencyBucketBounds(i) + if i+1 != len(s.latency) && max <= minLatency { + continue + } + if maxLatency != 0 && maxLatency < min { + continue + } + for _, sd := range b.buffer { + if sd == nil { + break + } + if minLatency != 0 || maxLatency != 0 { + d := sd.EndTime.Sub(sd.StartTime) + if d < minLatency { + continue + } + if maxLatency != 0 && d > maxLatency { + continue + } + } + out = append(out, sd) + } + } + return out +} + +// spanStore keeps track of spans stored for a particular span name. +// +// It contains all active spans; a sample of spans for failed requests, +// categorized by error code; and a sample of spans for successful requests, +// bucketed by latency. +type spanStore struct { + mu sync.Mutex // protects everything below. + active map[*Span]struct{} + errors map[int32]*bucket + latency []bucket + maxSpansPerErrorBucket int +} + +// newSpanStore creates a span store. +func newSpanStore(name string, latencyBucketSize int, errorBucketSize int) *spanStore { + s := &spanStore{ + active: make(map[*Span]struct{}), + latency: make([]bucket, len(defaultLatencies)+1), + maxSpansPerErrorBucket: errorBucketSize, + } + for i := range s.latency { + s.latency[i] = makeBucket(latencyBucketSize) + } + return s +} + +// spanStoreForName returns the spanStore for the given name. +// +// It returns nil if it doesn't exist. +func spanStoreForName(name string) *spanStore { + var s *spanStore + ssmu.RLock() + s, _ = spanStores[name] + ssmu.RUnlock() + return s +} + +// spanStoreForNameCreateIfNew returns the spanStore for the given name. +// +// It creates it if it didn't exist. +func spanStoreForNameCreateIfNew(name string) *spanStore { + ssmu.RLock() + s, ok := spanStores[name] + ssmu.RUnlock() + if ok { + return s + } + ssmu.Lock() + defer ssmu.Unlock() + s, ok = spanStores[name] + if ok { + return s + } + s = newSpanStore(name, defaultBucketSize, defaultBucketSize) + spanStores[name] = s + return s +} + +// spanStoreSetSize resizes the spanStore for the given name. +// +// It creates it if it didn't exist. +func spanStoreSetSize(name string, latencyBucketSize int, errorBucketSize int) { + ssmu.RLock() + s, ok := spanStores[name] + ssmu.RUnlock() + if ok { + s.resize(latencyBucketSize, errorBucketSize) + return + } + ssmu.Lock() + defer ssmu.Unlock() + s, ok = spanStores[name] + if ok { + s.resize(latencyBucketSize, errorBucketSize) + return + } + s = newSpanStore(name, latencyBucketSize, errorBucketSize) + spanStores[name] = s +} + +func (s *spanStore) resize(latencyBucketSize int, errorBucketSize int) { + s.mu.Lock() + for i := range s.latency { + s.latency[i].resize(latencyBucketSize) + } + for _, b := range s.errors { + b.resize(errorBucketSize) + } + s.maxSpansPerErrorBucket = errorBucketSize + s.mu.Unlock() +} + +// add adds a span to the active bucket of the spanStore. +func (s *spanStore) add(span *Span) { + s.mu.Lock() + s.active[span] = struct{}{} + s.mu.Unlock() +} + +// finished removes a span from the active set, and adds a corresponding +// SpanData to a latency or error bucket. +func (s *spanStore) finished(span *Span, sd *SpanData) { + latency := sd.EndTime.Sub(sd.StartTime) + if latency < 0 { + latency = 0 + } + code := sd.Status.Code + + s.mu.Lock() + delete(s.active, span) + if code == 0 { + s.latency[latencyBucket(latency)].add(sd) + } else { + if s.errors == nil { + s.errors = make(map[int32]*bucket) + } + if b := s.errors[code]; b != nil { + b.add(sd) + } else { + b := makeBucket(s.maxSpansPerErrorBucket) + s.errors[code] = &b + b.add(sd) + } + } + s.mu.Unlock() +} diff --git a/vendor/go.opencensus.io/trace/status_codes.go b/vendor/go.opencensus.io/trace/status_codes.go new file mode 100644 index 00000000..ec60effd --- /dev/null +++ b/vendor/go.opencensus.io/trace/status_codes.go @@ -0,0 +1,37 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package trace + +// Status codes for use with Span.SetStatus. These correspond to the status +// codes used by gRPC defined here: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto +const ( + StatusCodeOK = 0 + StatusCodeCancelled = 1 + StatusCodeUnknown = 2 + StatusCodeInvalidArgument = 3 + StatusCodeDeadlineExceeded = 4 + StatusCodeNotFound = 5 + StatusCodeAlreadyExists = 6 + StatusCodePermissionDenied = 7 + StatusCodeResourceExhausted = 8 + StatusCodeFailedPrecondition = 9 + StatusCodeAborted = 10 + StatusCodeOutOfRange = 11 + StatusCodeUnimplemented = 12 + StatusCodeInternal = 13 + StatusCodeUnavailable = 14 + StatusCodeDataLoss = 15 + StatusCodeUnauthenticated = 16 +) diff --git a/vendor/go.opencensus.io/trace/trace.go b/vendor/go.opencensus.io/trace/trace.go new file mode 100644 index 00000000..38ead7bf --- /dev/null +++ b/vendor/go.opencensus.io/trace/trace.go @@ -0,0 +1,598 @@ +// Copyright 2017, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package trace + +import ( + "context" + crand "crypto/rand" + "encoding/binary" + "fmt" + "math/rand" + "sync" + "sync/atomic" + "time" + + "go.opencensus.io/internal" + "go.opencensus.io/trace/tracestate" +) + +// Span represents a span of a trace. It has an associated SpanContext, and +// stores data accumulated while the span is active. +// +// Ideally users should interact with Spans by calling the functions in this +// package that take a Context parameter. +type Span struct { + // data contains information recorded about the span. + // + // It will be non-nil if we are exporting the span or recording events for it. + // Otherwise, data is nil, and the Span is simply a carrier for the + // SpanContext, so that the trace ID is propagated. + data *SpanData + mu sync.Mutex // protects the contents of *data (but not the pointer value.) + spanContext SpanContext + + // lruAttributes are capped at configured limit. When the capacity is reached an oldest entry + // is removed to create room for a new entry. + lruAttributes *lruMap + + // annotations are stored in FIFO queue capped by configured limit. + annotations *evictedQueue + + // messageEvents are stored in FIFO queue capped by configured limit. + messageEvents *evictedQueue + + // links are stored in FIFO queue capped by configured limit. + links *evictedQueue + + // spanStore is the spanStore this span belongs to, if any, otherwise it is nil. + *spanStore + endOnce sync.Once + + executionTracerTaskEnd func() // ends the execution tracer span +} + +// IsRecordingEvents returns true if events are being recorded for this span. +// Use this check to avoid computing expensive annotations when they will never +// be used. +func (s *Span) IsRecordingEvents() bool { + if s == nil { + return false + } + return s.data != nil +} + +// TraceOptions contains options associated with a trace span. +type TraceOptions uint32 + +// IsSampled returns true if the span will be exported. +func (sc SpanContext) IsSampled() bool { + return sc.TraceOptions.IsSampled() +} + +// setIsSampled sets the TraceOptions bit that determines whether the span will be exported. +func (sc *SpanContext) setIsSampled(sampled bool) { + if sampled { + sc.TraceOptions |= 1 + } else { + sc.TraceOptions &= ^TraceOptions(1) + } +} + +// IsSampled returns true if the span will be exported. +func (t TraceOptions) IsSampled() bool { + return t&1 == 1 +} + +// SpanContext contains the state that must propagate across process boundaries. +// +// SpanContext is not an implementation of context.Context. +// TODO: add reference to external Census docs for SpanContext. +type SpanContext struct { + TraceID TraceID + SpanID SpanID + TraceOptions TraceOptions + Tracestate *tracestate.Tracestate +} + +type contextKey struct{} + +// FromContext returns the Span stored in a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Span { + s, _ := ctx.Value(contextKey{}).(*Span) + return s +} + +// NewContext returns a new context with the given Span attached. +func NewContext(parent context.Context, s *Span) context.Context { + return context.WithValue(parent, contextKey{}, s) +} + +// All available span kinds. Span kind must be either one of these values. +const ( + SpanKindUnspecified = iota + SpanKindServer + SpanKindClient +) + +// StartOptions contains options concerning how a span is started. +type StartOptions struct { + // Sampler to consult for this Span. If provided, it is always consulted. + // + // If not provided, then the behavior differs based on whether + // the parent of this Span is remote, local, or there is no parent. + // In the case of a remote parent or no parent, the + // default sampler (see Config) will be consulted. Otherwise, + // when there is a non-remote parent, no new sampling decision will be made: + // we will preserve the sampling of the parent. + Sampler Sampler + + // SpanKind represents the kind of a span. If none is set, + // SpanKindUnspecified is used. + SpanKind int +} + +// StartOption apply changes to StartOptions. +type StartOption func(*StartOptions) + +// WithSpanKind makes new spans to be created with the given kind. +func WithSpanKind(spanKind int) StartOption { + return func(o *StartOptions) { + o.SpanKind = spanKind + } +} + +// WithSampler makes new spans to be be created with a custom sampler. +// Otherwise, the global sampler is used. +func WithSampler(sampler Sampler) StartOption { + return func(o *StartOptions) { + o.Sampler = sampler + } +} + +// StartSpan starts a new child span of the current span in the context. If +// there is no span in the context, creates a new trace and span. +// +// Returned context contains the newly created span. You can use it to +// propagate the returned span in process. +func StartSpan(ctx context.Context, name string, o ...StartOption) (context.Context, *Span) { + var opts StartOptions + var parent SpanContext + if p := FromContext(ctx); p != nil { + p.addChild() + parent = p.spanContext + } + for _, op := range o { + op(&opts) + } + span := startSpanInternal(name, parent != SpanContext{}, parent, false, opts) + + ctx, end := startExecutionTracerTask(ctx, name) + span.executionTracerTaskEnd = end + return NewContext(ctx, span), span +} + +// StartSpanWithRemoteParent starts a new child span of the span from the given parent. +// +// If the incoming context contains a parent, it ignores. StartSpanWithRemoteParent is +// preferred for cases where the parent is propagated via an incoming request. +// +// Returned context contains the newly created span. You can use it to +// propagate the returned span in process. +func StartSpanWithRemoteParent(ctx context.Context, name string, parent SpanContext, o ...StartOption) (context.Context, *Span) { + var opts StartOptions + for _, op := range o { + op(&opts) + } + span := startSpanInternal(name, parent != SpanContext{}, parent, true, opts) + ctx, end := startExecutionTracerTask(ctx, name) + span.executionTracerTaskEnd = end + return NewContext(ctx, span), span +} + +func startSpanInternal(name string, hasParent bool, parent SpanContext, remoteParent bool, o StartOptions) *Span { + span := &Span{} + span.spanContext = parent + + cfg := config.Load().(*Config) + + if !hasParent { + span.spanContext.TraceID = cfg.IDGenerator.NewTraceID() + } + span.spanContext.SpanID = cfg.IDGenerator.NewSpanID() + sampler := cfg.DefaultSampler + + if !hasParent || remoteParent || o.Sampler != nil { + // If this span is the child of a local span and no Sampler is set in the + // options, keep the parent's TraceOptions. + // + // Otherwise, consult the Sampler in the options if it is non-nil, otherwise + // the default sampler. + if o.Sampler != nil { + sampler = o.Sampler + } + span.spanContext.setIsSampled(sampler(SamplingParameters{ + ParentContext: parent, + TraceID: span.spanContext.TraceID, + SpanID: span.spanContext.SpanID, + Name: name, + HasRemoteParent: remoteParent}).Sample) + } + + if !internal.LocalSpanStoreEnabled && !span.spanContext.IsSampled() { + return span + } + + span.data = &SpanData{ + SpanContext: span.spanContext, + StartTime: time.Now(), + SpanKind: o.SpanKind, + Name: name, + HasRemoteParent: remoteParent, + } + span.lruAttributes = newLruMap(cfg.MaxAttributesPerSpan) + span.annotations = newEvictedQueue(cfg.MaxAnnotationEventsPerSpan) + span.messageEvents = newEvictedQueue(cfg.MaxMessageEventsPerSpan) + span.links = newEvictedQueue(cfg.MaxLinksPerSpan) + + if hasParent { + span.data.ParentSpanID = parent.SpanID + } + if internal.LocalSpanStoreEnabled { + var ss *spanStore + ss = spanStoreForNameCreateIfNew(name) + if ss != nil { + span.spanStore = ss + ss.add(span) + } + } + + return span +} + +// End ends the span. +func (s *Span) End() { + if s == nil { + return + } + if s.executionTracerTaskEnd != nil { + s.executionTracerTaskEnd() + } + if !s.IsRecordingEvents() { + return + } + s.endOnce.Do(func() { + exp, _ := exporters.Load().(exportersMap) + mustExport := s.spanContext.IsSampled() && len(exp) > 0 + if s.spanStore != nil || mustExport { + sd := s.makeSpanData() + sd.EndTime = internal.MonotonicEndTime(sd.StartTime) + if s.spanStore != nil { + s.spanStore.finished(s, sd) + } + if mustExport { + for e := range exp { + e.ExportSpan(sd) + } + } + } + }) +} + +// makeSpanData produces a SpanData representing the current state of the Span. +// It requires that s.data is non-nil. +func (s *Span) makeSpanData() *SpanData { + var sd SpanData + s.mu.Lock() + sd = *s.data + if s.lruAttributes.simpleLruMap.Len() > 0 { + sd.Attributes = s.lruAttributesToAttributeMap() + sd.DroppedAttributeCount = s.lruAttributes.droppedCount + } + if len(s.annotations.queue) > 0 { + sd.Annotations = s.interfaceArrayToAnnotationArray() + sd.DroppedAnnotationCount = s.annotations.droppedCount + } + if len(s.messageEvents.queue) > 0 { + sd.MessageEvents = s.interfaceArrayToMessageEventArray() + sd.DroppedMessageEventCount = s.messageEvents.droppedCount + } + if len(s.links.queue) > 0 { + sd.Links = s.interfaceArrayToLinksArray() + sd.DroppedLinkCount = s.links.droppedCount + } + s.mu.Unlock() + return &sd +} + +// SpanContext returns the SpanContext of the span. +func (s *Span) SpanContext() SpanContext { + if s == nil { + return SpanContext{} + } + return s.spanContext +} + +// SetName sets the name of the span, if it is recording events. +func (s *Span) SetName(name string) { + if !s.IsRecordingEvents() { + return + } + s.mu.Lock() + s.data.Name = name + s.mu.Unlock() +} + +// SetStatus sets the status of the span, if it is recording events. +func (s *Span) SetStatus(status Status) { + if !s.IsRecordingEvents() { + return + } + s.mu.Lock() + s.data.Status = status + s.mu.Unlock() +} + +func (s *Span) interfaceArrayToLinksArray() []Link { + linksArr := make([]Link, 0) + for _, value := range s.links.queue { + linksArr = append(linksArr, value.(Link)) + } + return linksArr +} + +func (s *Span) interfaceArrayToMessageEventArray() []MessageEvent { + messageEventArr := make([]MessageEvent, 0) + for _, value := range s.messageEvents.queue { + messageEventArr = append(messageEventArr, value.(MessageEvent)) + } + return messageEventArr +} + +func (s *Span) interfaceArrayToAnnotationArray() []Annotation { + annotationArr := make([]Annotation, 0) + for _, value := range s.annotations.queue { + annotationArr = append(annotationArr, value.(Annotation)) + } + return annotationArr +} + +func (s *Span) lruAttributesToAttributeMap() map[string]interface{} { + attributes := make(map[string]interface{}) + for _, key := range s.lruAttributes.simpleLruMap.Keys() { + value, ok := s.lruAttributes.simpleLruMap.Get(key) + if ok { + keyStr := key.(string) + attributes[keyStr] = value + } + } + return attributes +} + +func (s *Span) copyToCappedAttributes(attributes []Attribute) { + for _, a := range attributes { + s.lruAttributes.add(a.key, a.value) + } +} + +func (s *Span) addChild() { + if !s.IsRecordingEvents() { + return + } + s.mu.Lock() + s.data.ChildSpanCount++ + s.mu.Unlock() +} + +// AddAttributes sets attributes in the span. +// +// Existing attributes whose keys appear in the attributes parameter are overwritten. +func (s *Span) AddAttributes(attributes ...Attribute) { + if !s.IsRecordingEvents() { + return + } + s.mu.Lock() + s.copyToCappedAttributes(attributes) + s.mu.Unlock() +} + +// copyAttributes copies a slice of Attributes into a map. +func copyAttributes(m map[string]interface{}, attributes []Attribute) { + for _, a := range attributes { + m[a.key] = a.value + } +} + +func (s *Span) lazyPrintfInternal(attributes []Attribute, format string, a ...interface{}) { + now := time.Now() + msg := fmt.Sprintf(format, a...) + var m map[string]interface{} + s.mu.Lock() + if len(attributes) != 0 { + m = make(map[string]interface{}) + copyAttributes(m, attributes) + } + s.annotations.add(Annotation{ + Time: now, + Message: msg, + Attributes: m, + }) + s.mu.Unlock() +} + +func (s *Span) printStringInternal(attributes []Attribute, str string) { + now := time.Now() + var a map[string]interface{} + s.mu.Lock() + if len(attributes) != 0 { + a = make(map[string]interface{}) + copyAttributes(a, attributes) + } + s.annotations.add(Annotation{ + Time: now, + Message: str, + Attributes: a, + }) + s.mu.Unlock() +} + +// Annotate adds an annotation with attributes. +// Attributes can be nil. +func (s *Span) Annotate(attributes []Attribute, str string) { + if !s.IsRecordingEvents() { + return + } + s.printStringInternal(attributes, str) +} + +// Annotatef adds an annotation with attributes. +func (s *Span) Annotatef(attributes []Attribute, format string, a ...interface{}) { + if !s.IsRecordingEvents() { + return + } + s.lazyPrintfInternal(attributes, format, a...) +} + +// AddMessageSendEvent adds a message send event to the span. +// +// messageID is an identifier for the message, which is recommended to be +// unique in this span and the same between the send event and the receive +// event (this allows to identify a message between the sender and receiver). +// For example, this could be a sequence id. +func (s *Span) AddMessageSendEvent(messageID, uncompressedByteSize, compressedByteSize int64) { + if !s.IsRecordingEvents() { + return + } + now := time.Now() + s.mu.Lock() + s.messageEvents.add(MessageEvent{ + Time: now, + EventType: MessageEventTypeSent, + MessageID: messageID, + UncompressedByteSize: uncompressedByteSize, + CompressedByteSize: compressedByteSize, + }) + s.mu.Unlock() +} + +// AddMessageReceiveEvent adds a message receive event to the span. +// +// messageID is an identifier for the message, which is recommended to be +// unique in this span and the same between the send event and the receive +// event (this allows to identify a message between the sender and receiver). +// For example, this could be a sequence id. +func (s *Span) AddMessageReceiveEvent(messageID, uncompressedByteSize, compressedByteSize int64) { + if !s.IsRecordingEvents() { + return + } + now := time.Now() + s.mu.Lock() + s.messageEvents.add(MessageEvent{ + Time: now, + EventType: MessageEventTypeRecv, + MessageID: messageID, + UncompressedByteSize: uncompressedByteSize, + CompressedByteSize: compressedByteSize, + }) + s.mu.Unlock() +} + +// AddLink adds a link to the span. +func (s *Span) AddLink(l Link) { + if !s.IsRecordingEvents() { + return + } + s.mu.Lock() + s.links.add(l) + s.mu.Unlock() +} + +func (s *Span) String() string { + if s == nil { + return "" + } + if s.data == nil { + return fmt.Sprintf("span %s", s.spanContext.SpanID) + } + s.mu.Lock() + str := fmt.Sprintf("span %s %q", s.spanContext.SpanID, s.data.Name) + s.mu.Unlock() + return str +} + +var config atomic.Value // access atomically + +func init() { + gen := &defaultIDGenerator{} + // initialize traceID and spanID generators. + var rngSeed int64 + for _, p := range []interface{}{ + &rngSeed, &gen.traceIDAdd, &gen.nextSpanID, &gen.spanIDInc, + } { + binary.Read(crand.Reader, binary.LittleEndian, p) + } + gen.traceIDRand = rand.New(rand.NewSource(rngSeed)) + gen.spanIDInc |= 1 + + config.Store(&Config{ + DefaultSampler: ProbabilitySampler(defaultSamplingProbability), + IDGenerator: gen, + MaxAttributesPerSpan: DefaultMaxAttributesPerSpan, + MaxAnnotationEventsPerSpan: DefaultMaxAnnotationEventsPerSpan, + MaxMessageEventsPerSpan: DefaultMaxMessageEventsPerSpan, + MaxLinksPerSpan: DefaultMaxLinksPerSpan, + }) +} + +type defaultIDGenerator struct { + sync.Mutex + + // Please keep these as the first fields + // so that these 8 byte fields will be aligned on addresses + // divisible by 8, on both 32-bit and 64-bit machines when + // performing atomic increments and accesses. + // See: + // * https://github.com/census-instrumentation/opencensus-go/issues/587 + // * https://github.com/census-instrumentation/opencensus-go/issues/865 + // * https://golang.org/pkg/sync/atomic/#pkg-note-BUG + nextSpanID uint64 + spanIDInc uint64 + + traceIDAdd [2]uint64 + traceIDRand *rand.Rand +} + +// NewSpanID returns a non-zero span ID from a randomly-chosen sequence. +func (gen *defaultIDGenerator) NewSpanID() [8]byte { + var id uint64 + for id == 0 { + id = atomic.AddUint64(&gen.nextSpanID, gen.spanIDInc) + } + var sid [8]byte + binary.LittleEndian.PutUint64(sid[:], id) + return sid +} + +// NewTraceID returns a non-zero trace ID from a randomly-chosen sequence. +// mu should be held while this function is called. +func (gen *defaultIDGenerator) NewTraceID() [16]byte { + var tid [16]byte + // Construct the trace ID from two outputs of traceIDRand, with a constant + // added to each half for additional entropy. + gen.Lock() + binary.LittleEndian.PutUint64(tid[0:8], gen.traceIDRand.Uint64()+gen.traceIDAdd[0]) + binary.LittleEndian.PutUint64(tid[8:16], gen.traceIDRand.Uint64()+gen.traceIDAdd[1]) + gen.Unlock() + return tid +} diff --git a/vendor/go.opencensus.io/trace/trace_go11.go b/vendor/go.opencensus.io/trace/trace_go11.go new file mode 100644 index 00000000..b7d8aaf2 --- /dev/null +++ b/vendor/go.opencensus.io/trace/trace_go11.go @@ -0,0 +1,32 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build go1.11 + +package trace + +import ( + "context" + t "runtime/trace" +) + +func startExecutionTracerTask(ctx context.Context, name string) (context.Context, func()) { + if !t.IsEnabled() { + // Avoid additional overhead if + // runtime/trace is not enabled. + return ctx, func() {} + } + nctx, task := t.NewTask(ctx, name) + return nctx, task.End +} diff --git a/vendor/go.opencensus.io/trace/trace_nongo11.go b/vendor/go.opencensus.io/trace/trace_nongo11.go new file mode 100644 index 00000000..e2541985 --- /dev/null +++ b/vendor/go.opencensus.io/trace/trace_nongo11.go @@ -0,0 +1,25 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build !go1.11 + +package trace + +import ( + "context" +) + +func startExecutionTracerTask(ctx context.Context, name string) (context.Context, func()) { + return ctx, func() {} +} diff --git a/vendor/go.opencensus.io/trace/tracestate/tracestate.go b/vendor/go.opencensus.io/trace/tracestate/tracestate.go new file mode 100644 index 00000000..2d6c713e --- /dev/null +++ b/vendor/go.opencensus.io/trace/tracestate/tracestate.go @@ -0,0 +1,147 @@ +// Copyright 2018, OpenCensus Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package tracestate implements support for the Tracestate header of the +// W3C TraceContext propagation format. +package tracestate + +import ( + "fmt" + "regexp" +) + +const ( + keyMaxSize = 256 + valueMaxSize = 256 + maxKeyValuePairs = 32 +) + +const ( + keyWithoutVendorFormat = `[a-z][_0-9a-z\-\*\/]{0,255}` + keyWithVendorFormat = `[a-z][_0-9a-z\-\*\/]{0,240}@[a-z][_0-9a-z\-\*\/]{0,13}` + keyFormat = `(` + keyWithoutVendorFormat + `)|(` + keyWithVendorFormat + `)` + valueFormat = `[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]` +) + +var keyValidationRegExp = regexp.MustCompile(`^(` + keyFormat + `)$`) +var valueValidationRegExp = regexp.MustCompile(`^(` + valueFormat + `)$`) + +// Tracestate represents tracing-system specific context in a list of key-value pairs. Tracestate allows different +// vendors propagate additional information and inter-operate with their legacy Id formats. +type Tracestate struct { + entries []Entry +} + +// Entry represents one key-value pair in a list of key-value pair of Tracestate. +type Entry struct { + // Key is an opaque string up to 256 characters printable. It MUST begin with a lowercase letter, + // and can only contain lowercase letters a-z, digits 0-9, underscores _, dashes -, asterisks *, and + // forward slashes /. + Key string + + // Value is an opaque string up to 256 characters printable ASCII RFC0020 characters (i.e., the + // range 0x20 to 0x7E) except comma , and =. + Value string +} + +// Entries returns a slice of Entry. +func (ts *Tracestate) Entries() []Entry { + if ts == nil { + return nil + } + return ts.entries +} + +func (ts *Tracestate) remove(key string) *Entry { + for index, entry := range ts.entries { + if entry.Key == key { + ts.entries = append(ts.entries[:index], ts.entries[index+1:]...) + return &entry + } + } + return nil +} + +func (ts *Tracestate) add(entries []Entry) error { + for _, entry := range entries { + ts.remove(entry.Key) + } + if len(ts.entries)+len(entries) > maxKeyValuePairs { + return fmt.Errorf("adding %d key-value pairs to current %d pairs exceeds the limit of %d", + len(entries), len(ts.entries), maxKeyValuePairs) + } + ts.entries = append(entries, ts.entries...) + return nil +} + +func isValid(entry Entry) bool { + return keyValidationRegExp.MatchString(entry.Key) && + valueValidationRegExp.MatchString(entry.Value) +} + +func containsDuplicateKey(entries ...Entry) (string, bool) { + keyMap := make(map[string]int) + for _, entry := range entries { + if _, ok := keyMap[entry.Key]; ok { + return entry.Key, true + } + keyMap[entry.Key] = 1 + } + return "", false +} + +func areEntriesValid(entries ...Entry) (*Entry, bool) { + for _, entry := range entries { + if !isValid(entry) { + return &entry, false + } + } + return nil, true +} + +// New creates a Tracestate object from a parent and/or entries (key-value pair). +// Entries from the parent are copied if present. The entries passed to this function +// are inserted in front of those copied from the parent. If an entry copied from the +// parent contains the same key as one of the entry in entries then the entry copied +// from the parent is removed. See add func. +// +// An error is returned with nil Tracestate if +// 1. one or more entry in entries is invalid. +// 2. two or more entries in the input entries have the same key. +// 3. the number of entries combined from the parent and the input entries exceeds maxKeyValuePairs. +// (duplicate entry is counted only once). +func New(parent *Tracestate, entries ...Entry) (*Tracestate, error) { + if parent == nil && len(entries) == 0 { + return nil, nil + } + if entry, ok := areEntriesValid(entries...); !ok { + return nil, fmt.Errorf("key-value pair {%s, %s} is invalid", entry.Key, entry.Value) + } + + if key, duplicate := containsDuplicateKey(entries...); duplicate { + return nil, fmt.Errorf("contains duplicate keys (%s)", key) + } + + tracestate := Tracestate{} + + if parent != nil && len(parent.entries) > 0 { + tracestate.entries = append([]Entry{}, parent.entries...) + } + + err := tracestate.add(entries) + if err != nil { + return nil, err + } + return &tracestate, nil +} diff --git a/vendor/golang.org/x/oauth2/google/appengine.go b/vendor/golang.org/x/oauth2/google/appengine.go new file mode 100644 index 00000000..feb1157b --- /dev/null +++ b/vendor/golang.org/x/oauth2/google/appengine.go @@ -0,0 +1,38 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package google + +import ( + "context" + "time" + + "golang.org/x/oauth2" +) + +// Set at init time by appengine_gen1.go. If nil, we're not on App Engine standard first generation (<= Go 1.9) or App Engine flexible. +var appengineTokenFunc func(c context.Context, scopes ...string) (token string, expiry time.Time, err error) + +// Set at init time by appengine_gen1.go. If nil, we're not on App Engine standard first generation (<= Go 1.9) or App Engine flexible. +var appengineAppIDFunc func(c context.Context) string + +// AppEngineTokenSource returns a token source that fetches tokens from either +// the current application's service account or from the metadata server, +// depending on the App Engine environment. See below for environment-specific +// details. If you are implementing a 3-legged OAuth 2.0 flow on App Engine that +// involves user accounts, see oauth2.Config instead. +// +// First generation App Engine runtimes (<= Go 1.9): +// AppEngineTokenSource returns a token source that fetches tokens issued to the +// current App Engine application's service account. The provided context must have +// come from appengine.NewContext. +// +// Second generation App Engine runtimes (>= Go 1.11) and App Engine flexible: +// AppEngineTokenSource is DEPRECATED on second generation runtimes and on the +// flexible environment. It delegates to ComputeTokenSource, and the provided +// context and scopes are not used. Please use DefaultTokenSource (or ComputeTokenSource, +// which DefaultTokenSource will use in this case) instead. +func AppEngineTokenSource(ctx context.Context, scope ...string) oauth2.TokenSource { + return appEngineTokenSource(ctx, scope...) +} diff --git a/vendor/golang.org/x/oauth2/google/appengine_gen1.go b/vendor/golang.org/x/oauth2/google/appengine_gen1.go new file mode 100644 index 00000000..83dacac3 --- /dev/null +++ b/vendor/golang.org/x/oauth2/google/appengine_gen1.go @@ -0,0 +1,77 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build appengine + +// This file applies to App Engine first generation runtimes (<= Go 1.9). + +package google + +import ( + "context" + "sort" + "strings" + "sync" + + "golang.org/x/oauth2" + "google.golang.org/appengine" +) + +func init() { + appengineTokenFunc = appengine.AccessToken + appengineAppIDFunc = appengine.AppID +} + +// See comment on AppEngineTokenSource in appengine.go. +func appEngineTokenSource(ctx context.Context, scope ...string) oauth2.TokenSource { + scopes := append([]string{}, scope...) + sort.Strings(scopes) + return &gaeTokenSource{ + ctx: ctx, + scopes: scopes, + key: strings.Join(scopes, " "), + } +} + +// aeTokens helps the fetched tokens to be reused until their expiration. +var ( + aeTokensMu sync.Mutex + aeTokens = make(map[string]*tokenLock) // key is space-separated scopes +) + +type tokenLock struct { + mu sync.Mutex // guards t; held while fetching or updating t + t *oauth2.Token +} + +type gaeTokenSource struct { + ctx context.Context + scopes []string + key string // to aeTokens map; space-separated scopes +} + +func (ts *gaeTokenSource) Token() (*oauth2.Token, error) { + aeTokensMu.Lock() + tok, ok := aeTokens[ts.key] + if !ok { + tok = &tokenLock{} + aeTokens[ts.key] = tok + } + aeTokensMu.Unlock() + + tok.mu.Lock() + defer tok.mu.Unlock() + if tok.t.Valid() { + return tok.t, nil + } + access, exp, err := appengineTokenFunc(ts.ctx, ts.scopes...) + if err != nil { + return nil, err + } + tok.t = &oauth2.Token{ + AccessToken: access, + Expiry: exp, + } + return tok.t, nil +} diff --git a/vendor/golang.org/x/oauth2/google/appengine_gen2_flex.go b/vendor/golang.org/x/oauth2/google/appengine_gen2_flex.go new file mode 100644 index 00000000..04c2c221 --- /dev/null +++ b/vendor/golang.org/x/oauth2/google/appengine_gen2_flex.go @@ -0,0 +1,27 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !appengine + +// This file applies to App Engine second generation runtimes (>= Go 1.11) and App Engine flexible. + +package google + +import ( + "context" + "log" + "sync" + + "golang.org/x/oauth2" +) + +var logOnce sync.Once // only spam about deprecation once + +// See comment on AppEngineTokenSource in appengine.go. +func appEngineTokenSource(ctx context.Context, scope ...string) oauth2.TokenSource { + logOnce.Do(func() { + log.Print("google: AppEngineTokenSource is deprecated on App Engine standard second generation runtimes (>= Go 1.11) and App Engine flexible. Please use DefaultTokenSource or ComputeTokenSource.") + }) + return ComputeTokenSource("") +} diff --git a/vendor/golang.org/x/oauth2/google/default.go b/vendor/golang.org/x/oauth2/google/default.go new file mode 100644 index 00000000..ad2c0923 --- /dev/null +++ b/vendor/golang.org/x/oauth2/google/default.go @@ -0,0 +1,154 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package google + +import ( + "context" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "os" + "path/filepath" + "runtime" + + "cloud.google.com/go/compute/metadata" + "golang.org/x/oauth2" +) + +// Credentials holds Google credentials, including "Application Default Credentials". +// For more details, see: +// https://developers.google.com/accounts/docs/application-default-credentials +type Credentials struct { + ProjectID string // may be empty + TokenSource oauth2.TokenSource + + // JSON contains the raw bytes from a JSON credentials file. + // This field may be nil if authentication is provided by the + // environment and not with a credentials file, e.g. when code is + // running on Google Cloud Platform. + JSON []byte +} + +// DefaultCredentials is the old name of Credentials. +// +// Deprecated: use Credentials instead. +type DefaultCredentials = Credentials + +// DefaultClient returns an HTTP Client that uses the +// DefaultTokenSource to obtain authentication credentials. +func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) { + ts, err := DefaultTokenSource(ctx, scope...) + if err != nil { + return nil, err + } + return oauth2.NewClient(ctx, ts), nil +} + +// DefaultTokenSource returns the token source for +// "Application Default Credentials". +// It is a shortcut for FindDefaultCredentials(ctx, scope).TokenSource. +func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSource, error) { + creds, err := FindDefaultCredentials(ctx, scope...) + if err != nil { + return nil, err + } + return creds.TokenSource, nil +} + +// FindDefaultCredentials searches for "Application Default Credentials". +// +// It looks for credentials in the following places, +// preferring the first location found: +// +// 1. A JSON file whose path is specified by the +// GOOGLE_APPLICATION_CREDENTIALS environment variable. +// 2. A JSON file in a location known to the gcloud command-line tool. +// On Windows, this is %APPDATA%/gcloud/application_default_credentials.json. +// On other systems, $HOME/.config/gcloud/application_default_credentials.json. +// 3. On Google App Engine standard first generation runtimes (<= Go 1.9) it uses +// the appengine.AccessToken function. +// 4. On Google Compute Engine, Google App Engine standard second generation runtimes +// (>= Go 1.11), and Google App Engine flexible environment, it fetches +// credentials from the metadata server. +func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials, error) { + // First, try the environment variable. + const envVar = "GOOGLE_APPLICATION_CREDENTIALS" + if filename := os.Getenv(envVar); filename != "" { + creds, err := readCredentialsFile(ctx, filename, scopes) + if err != nil { + return nil, fmt.Errorf("google: error getting credentials using %v environment variable: %v", envVar, err) + } + return creds, nil + } + + // Second, try a well-known file. + filename := wellKnownFile() + if creds, err := readCredentialsFile(ctx, filename, scopes); err == nil { + return creds, nil + } else if !os.IsNotExist(err) { + return nil, fmt.Errorf("google: error getting credentials using well-known file (%v): %v", filename, err) + } + + // Third, if we're on a Google App Engine standard first generation runtime (<= Go 1.9) + // use those credentials. App Engine standard second generation runtimes (>= Go 1.11) + // and App Engine flexible use ComputeTokenSource and the metadata server. + if appengineTokenFunc != nil { + return &DefaultCredentials{ + ProjectID: appengineAppIDFunc(ctx), + TokenSource: AppEngineTokenSource(ctx, scopes...), + }, nil + } + + // Fourth, if we're on Google Compute Engine, an App Engine standard second generation runtime, + // or App Engine flexible, use the metadata server. + if metadata.OnGCE() { + id, _ := metadata.ProjectID() + return &DefaultCredentials{ + ProjectID: id, + TokenSource: ComputeTokenSource("", scopes...), + }, nil + } + + // None are found; return helpful error. + const url = "https://developers.google.com/accounts/docs/application-default-credentials" + return nil, fmt.Errorf("google: could not find default credentials. See %v for more information.", url) +} + +// CredentialsFromJSON obtains Google credentials from a JSON value. The JSON can +// represent either a Google Developers Console client_credentials.json file (as in +// ConfigFromJSON) or a Google Developers service account key file (as in +// JWTConfigFromJSON). +func CredentialsFromJSON(ctx context.Context, jsonData []byte, scopes ...string) (*Credentials, error) { + var f credentialsFile + if err := json.Unmarshal(jsonData, &f); err != nil { + return nil, err + } + ts, err := f.tokenSource(ctx, append([]string(nil), scopes...)) + if err != nil { + return nil, err + } + return &DefaultCredentials{ + ProjectID: f.ProjectID, + TokenSource: ts, + JSON: jsonData, + }, nil +} + +func wellKnownFile() string { + const f = "application_default_credentials.json" + if runtime.GOOS == "windows" { + return filepath.Join(os.Getenv("APPDATA"), "gcloud", f) + } + return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", f) +} + +func readCredentialsFile(ctx context.Context, filename string, scopes []string) (*DefaultCredentials, error) { + b, err := ioutil.ReadFile(filename) + if err != nil { + return nil, err + } + return CredentialsFromJSON(ctx, b, scopes...) +} diff --git a/vendor/golang.org/x/oauth2/google/doc.go b/vendor/golang.org/x/oauth2/google/doc.go new file mode 100644 index 00000000..73be6290 --- /dev/null +++ b/vendor/golang.org/x/oauth2/google/doc.go @@ -0,0 +1,40 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package google provides support for making OAuth2 authorized and authenticated +// HTTP requests to Google APIs. It supports the Web server flow, client-side +// credentials, service accounts, Google Compute Engine service accounts, and Google +// App Engine service accounts. +// +// A brief overview of the package follows. For more information, please read +// https://developers.google.com/accounts/docs/OAuth2 +// and +// https://developers.google.com/accounts/docs/application-default-credentials. +// +// OAuth2 Configs +// +// Two functions in this package return golang.org/x/oauth2.Config values from Google credential +// data. Google supports two JSON formats for OAuth2 credentials: one is handled by ConfigFromJSON, +// the other by JWTConfigFromJSON. The returned Config can be used to obtain a TokenSource or +// create an http.Client. +// +// +// Credentials +// +// The Credentials type represents Google credentials, including Application Default +// Credentials. +// +// Use FindDefaultCredentials to obtain Application Default Credentials. +// FindDefaultCredentials looks in some well-known places for a credentials file, and +// will call AppEngineTokenSource or ComputeTokenSource as needed. +// +// DefaultClient and DefaultTokenSource are convenience methods. They first call FindDefaultCredentials, +// then use the credentials to construct an http.Client or an oauth2.TokenSource. +// +// Use CredentialsFromJSON to obtain credentials from either of the two JSON formats +// described in OAuth2 Configs, above. The TokenSource in the returned value is the +// same as the one obtained from the oauth2.Config returned from ConfigFromJSON or +// JWTConfigFromJSON, but the Credentials may contain additional information +// that is useful is some circumstances. +package google // import "golang.org/x/oauth2/google" diff --git a/vendor/golang.org/x/oauth2/google/google.go b/vendor/golang.org/x/oauth2/google/google.go new file mode 100644 index 00000000..81de32b3 --- /dev/null +++ b/vendor/golang.org/x/oauth2/google/google.go @@ -0,0 +1,209 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package google + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/url" + "strings" + "time" + + "cloud.google.com/go/compute/metadata" + "golang.org/x/oauth2" + "golang.org/x/oauth2/jwt" +) + +// Endpoint is Google's OAuth 2.0 endpoint. +var Endpoint = oauth2.Endpoint{ + AuthURL: "https://accounts.google.com/o/oauth2/auth", + TokenURL: "https://oauth2.googleapis.com/token", + AuthStyle: oauth2.AuthStyleInParams, +} + +// JWTTokenURL is Google's OAuth 2.0 token URL to use with the JWT flow. +const JWTTokenURL = "https://oauth2.googleapis.com/token" + +// ConfigFromJSON uses a Google Developers Console client_credentials.json +// file to construct a config. +// client_credentials.json can be downloaded from +// https://console.developers.google.com, under "Credentials". Download the Web +// application credentials in the JSON format and provide the contents of the +// file as jsonKey. +func ConfigFromJSON(jsonKey []byte, scope ...string) (*oauth2.Config, error) { + type cred struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + RedirectURIs []string `json:"redirect_uris"` + AuthURI string `json:"auth_uri"` + TokenURI string `json:"token_uri"` + } + var j struct { + Web *cred `json:"web"` + Installed *cred `json:"installed"` + } + if err := json.Unmarshal(jsonKey, &j); err != nil { + return nil, err + } + var c *cred + switch { + case j.Web != nil: + c = j.Web + case j.Installed != nil: + c = j.Installed + default: + return nil, fmt.Errorf("oauth2/google: no credentials found") + } + if len(c.RedirectURIs) < 1 { + return nil, errors.New("oauth2/google: missing redirect URL in the client_credentials.json") + } + return &oauth2.Config{ + ClientID: c.ClientID, + ClientSecret: c.ClientSecret, + RedirectURL: c.RedirectURIs[0], + Scopes: scope, + Endpoint: oauth2.Endpoint{ + AuthURL: c.AuthURI, + TokenURL: c.TokenURI, + }, + }, nil +} + +// JWTConfigFromJSON uses a Google Developers service account JSON key file to read +// the credentials that authorize and authenticate the requests. +// Create a service account on "Credentials" for your project at +// https://console.developers.google.com to download a JSON key file. +func JWTConfigFromJSON(jsonKey []byte, scope ...string) (*jwt.Config, error) { + var f credentialsFile + if err := json.Unmarshal(jsonKey, &f); err != nil { + return nil, err + } + if f.Type != serviceAccountKey { + return nil, fmt.Errorf("google: read JWT from JSON credentials: 'type' field is %q (expected %q)", f.Type, serviceAccountKey) + } + scope = append([]string(nil), scope...) // copy + return f.jwtConfig(scope), nil +} + +// JSON key file types. +const ( + serviceAccountKey = "service_account" + userCredentialsKey = "authorized_user" +) + +// credentialsFile is the unmarshalled representation of a credentials file. +type credentialsFile struct { + Type string `json:"type"` // serviceAccountKey or userCredentialsKey + + // Service Account fields + ClientEmail string `json:"client_email"` + PrivateKeyID string `json:"private_key_id"` + PrivateKey string `json:"private_key"` + TokenURL string `json:"token_uri"` + ProjectID string `json:"project_id"` + + // User Credential fields + // (These typically come from gcloud auth.) + ClientSecret string `json:"client_secret"` + ClientID string `json:"client_id"` + RefreshToken string `json:"refresh_token"` +} + +func (f *credentialsFile) jwtConfig(scopes []string) *jwt.Config { + cfg := &jwt.Config{ + Email: f.ClientEmail, + PrivateKey: []byte(f.PrivateKey), + PrivateKeyID: f.PrivateKeyID, + Scopes: scopes, + TokenURL: f.TokenURL, + } + if cfg.TokenURL == "" { + cfg.TokenURL = JWTTokenURL + } + return cfg +} + +func (f *credentialsFile) tokenSource(ctx context.Context, scopes []string) (oauth2.TokenSource, error) { + switch f.Type { + case serviceAccountKey: + cfg := f.jwtConfig(scopes) + return cfg.TokenSource(ctx), nil + case userCredentialsKey: + cfg := &oauth2.Config{ + ClientID: f.ClientID, + ClientSecret: f.ClientSecret, + Scopes: scopes, + Endpoint: Endpoint, + } + tok := &oauth2.Token{RefreshToken: f.RefreshToken} + return cfg.TokenSource(ctx, tok), nil + case "": + return nil, errors.New("missing 'type' field in credentials") + default: + return nil, fmt.Errorf("unknown credential type: %q", f.Type) + } +} + +// ComputeTokenSource returns a token source that fetches access tokens +// from Google Compute Engine (GCE)'s metadata server. It's only valid to use +// this token source if your program is running on a GCE instance. +// If no account is specified, "default" is used. +// If no scopes are specified, a set of default scopes are automatically granted. +// Further information about retrieving access tokens from the GCE metadata +// server can be found at https://cloud.google.com/compute/docs/authentication. +func ComputeTokenSource(account string, scope ...string) oauth2.TokenSource { + return oauth2.ReuseTokenSource(nil, computeSource{account: account, scopes: scope}) +} + +type computeSource struct { + account string + scopes []string +} + +func (cs computeSource) Token() (*oauth2.Token, error) { + if !metadata.OnGCE() { + return nil, errors.New("oauth2/google: can't get a token from the metadata service; not running on GCE") + } + acct := cs.account + if acct == "" { + acct = "default" + } + tokenURI := "instance/service-accounts/" + acct + "/token" + if len(cs.scopes) > 0 { + v := url.Values{} + v.Set("scopes", strings.Join(cs.scopes, ",")) + tokenURI = tokenURI + "?" + v.Encode() + } + tokenJSON, err := metadata.Get(tokenURI) + if err != nil { + return nil, err + } + var res struct { + AccessToken string `json:"access_token"` + ExpiresInSec int `json:"expires_in"` + TokenType string `json:"token_type"` + } + err = json.NewDecoder(strings.NewReader(tokenJSON)).Decode(&res) + if err != nil { + return nil, fmt.Errorf("oauth2/google: invalid token JSON from metadata: %v", err) + } + if res.ExpiresInSec == 0 || res.AccessToken == "" { + return nil, fmt.Errorf("oauth2/google: incomplete token received from metadata") + } + tok := &oauth2.Token{ + AccessToken: res.AccessToken, + TokenType: res.TokenType, + Expiry: time.Now().Add(time.Duration(res.ExpiresInSec) * time.Second), + } + // NOTE(cbro): add hidden metadata about where the token is from. + // This is needed for detection by client libraries to know that credentials come from the metadata server. + // This may be removed in a future version of this library. + return tok.WithExtra(map[string]interface{}{ + "oauth2.google.tokenSource": "compute-metadata", + "oauth2.google.serviceAccount": acct, + }), nil +} diff --git a/vendor/golang.org/x/oauth2/google/jwt.go b/vendor/golang.org/x/oauth2/google/jwt.go new file mode 100644 index 00000000..b0fdb3a8 --- /dev/null +++ b/vendor/golang.org/x/oauth2/google/jwt.go @@ -0,0 +1,74 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package google + +import ( + "crypto/rsa" + "fmt" + "time" + + "golang.org/x/oauth2" + "golang.org/x/oauth2/internal" + "golang.org/x/oauth2/jws" +) + +// JWTAccessTokenSourceFromJSON uses a Google Developers service account JSON +// key file to read the credentials that authorize and authenticate the +// requests, and returns a TokenSource that does not use any OAuth2 flow but +// instead creates a JWT and sends that as the access token. +// The audience is typically a URL that specifies the scope of the credentials. +// +// Note that this is not a standard OAuth flow, but rather an +// optimization supported by a few Google services. +// Unless you know otherwise, you should use JWTConfigFromJSON instead. +func JWTAccessTokenSourceFromJSON(jsonKey []byte, audience string) (oauth2.TokenSource, error) { + cfg, err := JWTConfigFromJSON(jsonKey) + if err != nil { + return nil, fmt.Errorf("google: could not parse JSON key: %v", err) + } + pk, err := internal.ParseKey(cfg.PrivateKey) + if err != nil { + return nil, fmt.Errorf("google: could not parse key: %v", err) + } + ts := &jwtAccessTokenSource{ + email: cfg.Email, + audience: audience, + pk: pk, + pkID: cfg.PrivateKeyID, + } + tok, err := ts.Token() + if err != nil { + return nil, err + } + return oauth2.ReuseTokenSource(tok, ts), nil +} + +type jwtAccessTokenSource struct { + email, audience string + pk *rsa.PrivateKey + pkID string +} + +func (ts *jwtAccessTokenSource) Token() (*oauth2.Token, error) { + iat := time.Now() + exp := iat.Add(time.Hour) + cs := &jws.ClaimSet{ + Iss: ts.email, + Sub: ts.email, + Aud: ts.audience, + Iat: iat.Unix(), + Exp: exp.Unix(), + } + hdr := &jws.Header{ + Algorithm: "RS256", + Typ: "JWT", + KeyID: string(ts.pkID), + } + msg, err := jws.Encode(hdr, cs, ts.pk) + if err != nil { + return nil, fmt.Errorf("google: could not encode JWT: %v", err) + } + return &oauth2.Token{AccessToken: msg, TokenType: "Bearer", Expiry: exp}, nil +} diff --git a/vendor/golang.org/x/oauth2/google/sdk.go b/vendor/golang.org/x/oauth2/google/sdk.go new file mode 100644 index 00000000..456224bc --- /dev/null +++ b/vendor/golang.org/x/oauth2/google/sdk.go @@ -0,0 +1,201 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package google + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/user" + "path/filepath" + "runtime" + "strings" + "time" + + "golang.org/x/oauth2" +) + +type sdkCredentials struct { + Data []struct { + Credential struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + TokenExpiry *time.Time `json:"token_expiry"` + } `json:"credential"` + Key struct { + Account string `json:"account"` + Scope string `json:"scope"` + } `json:"key"` + } +} + +// An SDKConfig provides access to tokens from an account already +// authorized via the Google Cloud SDK. +type SDKConfig struct { + conf oauth2.Config + initialToken *oauth2.Token +} + +// NewSDKConfig creates an SDKConfig for the given Google Cloud SDK +// account. If account is empty, the account currently active in +// Google Cloud SDK properties is used. +// Google Cloud SDK credentials must be created by running `gcloud auth` +// before using this function. +// The Google Cloud SDK is available at https://cloud.google.com/sdk/. +func NewSDKConfig(account string) (*SDKConfig, error) { + configPath, err := sdkConfigPath() + if err != nil { + return nil, fmt.Errorf("oauth2/google: error getting SDK config path: %v", err) + } + credentialsPath := filepath.Join(configPath, "credentials") + f, err := os.Open(credentialsPath) + if err != nil { + return nil, fmt.Errorf("oauth2/google: failed to load SDK credentials: %v", err) + } + defer f.Close() + + var c sdkCredentials + if err := json.NewDecoder(f).Decode(&c); err != nil { + return nil, fmt.Errorf("oauth2/google: failed to decode SDK credentials from %q: %v", credentialsPath, err) + } + if len(c.Data) == 0 { + return nil, fmt.Errorf("oauth2/google: no credentials found in %q, run `gcloud auth login` to create one", credentialsPath) + } + if account == "" { + propertiesPath := filepath.Join(configPath, "properties") + f, err := os.Open(propertiesPath) + if err != nil { + return nil, fmt.Errorf("oauth2/google: failed to load SDK properties: %v", err) + } + defer f.Close() + ini, err := parseINI(f) + if err != nil { + return nil, fmt.Errorf("oauth2/google: failed to parse SDK properties %q: %v", propertiesPath, err) + } + core, ok := ini["core"] + if !ok { + return nil, fmt.Errorf("oauth2/google: failed to find [core] section in %v", ini) + } + active, ok := core["account"] + if !ok { + return nil, fmt.Errorf("oauth2/google: failed to find %q attribute in %v", "account", core) + } + account = active + } + + for _, d := range c.Data { + if account == "" || d.Key.Account == account { + if d.Credential.AccessToken == "" && d.Credential.RefreshToken == "" { + return nil, fmt.Errorf("oauth2/google: no token available for account %q", account) + } + var expiry time.Time + if d.Credential.TokenExpiry != nil { + expiry = *d.Credential.TokenExpiry + } + return &SDKConfig{ + conf: oauth2.Config{ + ClientID: d.Credential.ClientID, + ClientSecret: d.Credential.ClientSecret, + Scopes: strings.Split(d.Key.Scope, " "), + Endpoint: Endpoint, + RedirectURL: "oob", + }, + initialToken: &oauth2.Token{ + AccessToken: d.Credential.AccessToken, + RefreshToken: d.Credential.RefreshToken, + Expiry: expiry, + }, + }, nil + } + } + return nil, fmt.Errorf("oauth2/google: no such credentials for account %q", account) +} + +// Client returns an HTTP client using Google Cloud SDK credentials to +// authorize requests. The token will auto-refresh as necessary. The +// underlying http.RoundTripper will be obtained using the provided +// context. The returned client and its Transport should not be +// modified. +func (c *SDKConfig) Client(ctx context.Context) *http.Client { + return &http.Client{ + Transport: &oauth2.Transport{ + Source: c.TokenSource(ctx), + }, + } +} + +// TokenSource returns an oauth2.TokenSource that retrieve tokens from +// Google Cloud SDK credentials using the provided context. +// It will returns the current access token stored in the credentials, +// and refresh it when it expires, but it won't update the credentials +// with the new access token. +func (c *SDKConfig) TokenSource(ctx context.Context) oauth2.TokenSource { + return c.conf.TokenSource(ctx, c.initialToken) +} + +// Scopes are the OAuth 2.0 scopes the current account is authorized for. +func (c *SDKConfig) Scopes() []string { + return c.conf.Scopes +} + +func parseINI(ini io.Reader) (map[string]map[string]string, error) { + result := map[string]map[string]string{ + "": {}, // root section + } + scanner := bufio.NewScanner(ini) + currentSection := "" + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if strings.HasPrefix(line, ";") { + // comment. + continue + } + if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { + currentSection = strings.TrimSpace(line[1 : len(line)-1]) + result[currentSection] = map[string]string{} + continue + } + parts := strings.SplitN(line, "=", 2) + if len(parts) == 2 && parts[0] != "" { + result[currentSection][strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) + } + } + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("error scanning ini: %v", err) + } + return result, nil +} + +// sdkConfigPath tries to guess where the gcloud config is located. +// It can be overridden during tests. +var sdkConfigPath = func() (string, error) { + if runtime.GOOS == "windows" { + return filepath.Join(os.Getenv("APPDATA"), "gcloud"), nil + } + homeDir := guessUnixHomeDir() + if homeDir == "" { + return "", errors.New("unable to get current user home directory: os/user lookup failed; $HOME is empty") + } + return filepath.Join(homeDir, ".config", "gcloud"), nil +} + +func guessUnixHomeDir() string { + // Prefer $HOME over user.Current due to glibc bug: golang.org/issue/13470 + if v := os.Getenv("HOME"); v != "" { + return v + } + // Else, fall back to user.Current: + if u, err := user.Current(); err == nil { + return u.HomeDir + } + return "" +} diff --git a/vendor/golang.org/x/oauth2/jws/jws.go b/vendor/golang.org/x/oauth2/jws/jws.go new file mode 100644 index 00000000..683d2d27 --- /dev/null +++ b/vendor/golang.org/x/oauth2/jws/jws.go @@ -0,0 +1,182 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package jws provides a partial implementation +// of JSON Web Signature encoding and decoding. +// It exists to support the golang.org/x/oauth2 package. +// +// See RFC 7515. +// +// Deprecated: this package is not intended for public use and might be +// removed in the future. It exists for internal use only. +// Please switch to another JWS package or copy this package into your own +// source tree. +package jws // import "golang.org/x/oauth2/jws" + +import ( + "bytes" + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "strings" + "time" +) + +// ClaimSet contains information about the JWT signature including the +// permissions being requested (scopes), the target of the token, the issuer, +// the time the token was issued, and the lifetime of the token. +type ClaimSet struct { + Iss string `json:"iss"` // email address of the client_id of the application making the access token request + Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests + Aud string `json:"aud"` // descriptor of the intended target of the assertion (Optional). + Exp int64 `json:"exp"` // the expiration time of the assertion (seconds since Unix epoch) + Iat int64 `json:"iat"` // the time the assertion was issued (seconds since Unix epoch) + Typ string `json:"typ,omitempty"` // token type (Optional). + + // Email for which the application is requesting delegated access (Optional). + Sub string `json:"sub,omitempty"` + + // The old name of Sub. Client keeps setting Prn to be + // complaint with legacy OAuth 2.0 providers. (Optional) + Prn string `json:"prn,omitempty"` + + // See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3 + // This array is marshalled using custom code (see (c *ClaimSet) encode()). + PrivateClaims map[string]interface{} `json:"-"` +} + +func (c *ClaimSet) encode() (string, error) { + // Reverting time back for machines whose time is not perfectly in sync. + // If client machine's time is in the future according + // to Google servers, an access token will not be issued. + now := time.Now().Add(-10 * time.Second) + if c.Iat == 0 { + c.Iat = now.Unix() + } + if c.Exp == 0 { + c.Exp = now.Add(time.Hour).Unix() + } + if c.Exp < c.Iat { + return "", fmt.Errorf("jws: invalid Exp = %v; must be later than Iat = %v", c.Exp, c.Iat) + } + + b, err := json.Marshal(c) + if err != nil { + return "", err + } + + if len(c.PrivateClaims) == 0 { + return base64.RawURLEncoding.EncodeToString(b), nil + } + + // Marshal private claim set and then append it to b. + prv, err := json.Marshal(c.PrivateClaims) + if err != nil { + return "", fmt.Errorf("jws: invalid map of private claims %v", c.PrivateClaims) + } + + // Concatenate public and private claim JSON objects. + if !bytes.HasSuffix(b, []byte{'}'}) { + return "", fmt.Errorf("jws: invalid JSON %s", b) + } + if !bytes.HasPrefix(prv, []byte{'{'}) { + return "", fmt.Errorf("jws: invalid JSON %s", prv) + } + b[len(b)-1] = ',' // Replace closing curly brace with a comma. + b = append(b, prv[1:]...) // Append private claims. + return base64.RawURLEncoding.EncodeToString(b), nil +} + +// Header represents the header for the signed JWS payloads. +type Header struct { + // The algorithm used for signature. + Algorithm string `json:"alg"` + + // Represents the token type. + Typ string `json:"typ"` + + // The optional hint of which key is being used. + KeyID string `json:"kid,omitempty"` +} + +func (h *Header) encode() (string, error) { + b, err := json.Marshal(h) + if err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(b), nil +} + +// Decode decodes a claim set from a JWS payload. +func Decode(payload string) (*ClaimSet, error) { + // decode returned id token to get expiry + s := strings.Split(payload, ".") + if len(s) < 2 { + // TODO(jbd): Provide more context about the error. + return nil, errors.New("jws: invalid token received") + } + decoded, err := base64.RawURLEncoding.DecodeString(s[1]) + if err != nil { + return nil, err + } + c := &ClaimSet{} + err = json.NewDecoder(bytes.NewBuffer(decoded)).Decode(c) + return c, err +} + +// Signer returns a signature for the given data. +type Signer func(data []byte) (sig []byte, err error) + +// EncodeWithSigner encodes a header and claim set with the provided signer. +func EncodeWithSigner(header *Header, c *ClaimSet, sg Signer) (string, error) { + head, err := header.encode() + if err != nil { + return "", err + } + cs, err := c.encode() + if err != nil { + return "", err + } + ss := fmt.Sprintf("%s.%s", head, cs) + sig, err := sg([]byte(ss)) + if err != nil { + return "", err + } + return fmt.Sprintf("%s.%s", ss, base64.RawURLEncoding.EncodeToString(sig)), nil +} + +// Encode encodes a signed JWS with provided header and claim set. +// This invokes EncodeWithSigner using crypto/rsa.SignPKCS1v15 with the given RSA private key. +func Encode(header *Header, c *ClaimSet, key *rsa.PrivateKey) (string, error) { + sg := func(data []byte) (sig []byte, err error) { + h := sha256.New() + h.Write(data) + return rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, h.Sum(nil)) + } + return EncodeWithSigner(header, c, sg) +} + +// Verify tests whether the provided JWT token's signature was produced by the private key +// associated with the supplied public key. +func Verify(token string, key *rsa.PublicKey) error { + parts := strings.Split(token, ".") + if len(parts) != 3 { + return errors.New("jws: invalid token received, token must have 3 parts") + } + + signedContent := parts[0] + "." + parts[1] + signatureString, err := base64.RawURLEncoding.DecodeString(parts[2]) + if err != nil { + return err + } + + h := sha256.New() + h.Write([]byte(signedContent)) + return rsa.VerifyPKCS1v15(key, crypto.SHA256, h.Sum(nil), []byte(signatureString)) +} diff --git a/vendor/golang.org/x/oauth2/jwt/jwt.go b/vendor/golang.org/x/oauth2/jwt/jwt.go new file mode 100644 index 00000000..b2bf1829 --- /dev/null +++ b/vendor/golang.org/x/oauth2/jwt/jwt.go @@ -0,0 +1,185 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly +// known as "two-legged OAuth 2.0". +// +// See: https://tools.ietf.org/html/draft-ietf-oauth-jwt-bearer-12 +package jwt + +import ( + "context" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "net/http" + "net/url" + "strings" + "time" + + "golang.org/x/oauth2" + "golang.org/x/oauth2/internal" + "golang.org/x/oauth2/jws" +) + +var ( + defaultGrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer" + defaultHeader = &jws.Header{Algorithm: "RS256", Typ: "JWT"} +) + +// Config is the configuration for using JWT to fetch tokens, +// commonly known as "two-legged OAuth 2.0". +type Config struct { + // Email is the OAuth client identifier used when communicating with + // the configured OAuth provider. + Email string + + // PrivateKey contains the contents of an RSA private key or the + // contents of a PEM file that contains a private key. The provided + // private key is used to sign JWT payloads. + // PEM containers with a passphrase are not supported. + // Use the following command to convert a PKCS 12 file into a PEM. + // + // $ openssl pkcs12 -in key.p12 -out key.pem -nodes + // + PrivateKey []byte + + // PrivateKeyID contains an optional hint indicating which key is being + // used. + PrivateKeyID string + + // Subject is the optional user to impersonate. + Subject string + + // Scopes optionally specifies a list of requested permission scopes. + Scopes []string + + // TokenURL is the endpoint required to complete the 2-legged JWT flow. + TokenURL string + + // Expires optionally specifies how long the token is valid for. + Expires time.Duration + + // Audience optionally specifies the intended audience of the + // request. If empty, the value of TokenURL is used as the + // intended audience. + Audience string + + // PrivateClaims optionally specifies custom private claims in the JWT. + // See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3 + PrivateClaims map[string]interface{} + + // UseIDToken optionally specifies whether ID token should be used instead + // of access token when the server returns both. + UseIDToken bool +} + +// TokenSource returns a JWT TokenSource using the configuration +// in c and the HTTP client from the provided context. +func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSource { + return oauth2.ReuseTokenSource(nil, jwtSource{ctx, c}) +} + +// Client returns an HTTP client wrapping the context's +// HTTP transport and adding Authorization headers with tokens +// obtained from c. +// +// The returned client and its Transport should not be modified. +func (c *Config) Client(ctx context.Context) *http.Client { + return oauth2.NewClient(ctx, c.TokenSource(ctx)) +} + +// jwtSource is a source that always does a signed JWT request for a token. +// It should typically be wrapped with a reuseTokenSource. +type jwtSource struct { + ctx context.Context + conf *Config +} + +func (js jwtSource) Token() (*oauth2.Token, error) { + pk, err := internal.ParseKey(js.conf.PrivateKey) + if err != nil { + return nil, err + } + hc := oauth2.NewClient(js.ctx, nil) + claimSet := &jws.ClaimSet{ + Iss: js.conf.Email, + Scope: strings.Join(js.conf.Scopes, " "), + Aud: js.conf.TokenURL, + PrivateClaims: js.conf.PrivateClaims, + } + if subject := js.conf.Subject; subject != "" { + claimSet.Sub = subject + // prn is the old name of sub. Keep setting it + // to be compatible with legacy OAuth 2.0 providers. + claimSet.Prn = subject + } + if t := js.conf.Expires; t > 0 { + claimSet.Exp = time.Now().Add(t).Unix() + } + if aud := js.conf.Audience; aud != "" { + claimSet.Aud = aud + } + h := *defaultHeader + h.KeyID = js.conf.PrivateKeyID + payload, err := jws.Encode(&h, claimSet, pk) + if err != nil { + return nil, err + } + v := url.Values{} + v.Set("grant_type", defaultGrantType) + v.Set("assertion", payload) + resp, err := hc.PostForm(js.conf.TokenURL, v) + if err != nil { + return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) + } + if c := resp.StatusCode; c < 200 || c > 299 { + return nil, &oauth2.RetrieveError{ + Response: resp, + Body: body, + } + } + // tokenRes is the JSON response body. + var tokenRes struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + IDToken string `json:"id_token"` + ExpiresIn int64 `json:"expires_in"` // relative seconds from now + } + if err := json.Unmarshal(body, &tokenRes); err != nil { + return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) + } + token := &oauth2.Token{ + AccessToken: tokenRes.AccessToken, + TokenType: tokenRes.TokenType, + } + raw := make(map[string]interface{}) + json.Unmarshal(body, &raw) // no error checks for optional fields + token = token.WithExtra(raw) + + if secs := tokenRes.ExpiresIn; secs > 0 { + token.Expiry = time.Now().Add(time.Duration(secs) * time.Second) + } + if v := tokenRes.IDToken; v != "" { + // decode returned id token to get expiry + claimSet, err := jws.Decode(v) + if err != nil { + return nil, fmt.Errorf("oauth2: error decoding JWT token: %v", err) + } + token.Expiry = time.Unix(claimSet.Exp, 0) + } + if js.conf.UseIDToken { + if tokenRes.IDToken == "" { + return nil, fmt.Errorf("oauth2: response doesn't have JWT token") + } + token.AccessToken = tokenRes.IDToken + } + return token, nil +} diff --git a/vendor/google.golang.org/api/AUTHORS b/vendor/google.golang.org/api/AUTHORS new file mode 100644 index 00000000..f73b7257 --- /dev/null +++ b/vendor/google.golang.org/api/AUTHORS @@ -0,0 +1,10 @@ +# This is the official list of authors for copyright purposes. +# This file is distinct from the CONTRIBUTORS files. +# See the latter for an explanation. + +# Names should be added to this file as +# Name or Organization +# The email address is not required for organizations. + +# Please keep the list sorted. +Google Inc. diff --git a/vendor/google.golang.org/api/CONTRIBUTORS b/vendor/google.golang.org/api/CONTRIBUTORS new file mode 100644 index 00000000..fe55ebff --- /dev/null +++ b/vendor/google.golang.org/api/CONTRIBUTORS @@ -0,0 +1,55 @@ +# This is the official list of people who can contribute +# (and typically have contributed) code to the repository. +# The AUTHORS file lists the copyright holders; this file +# lists people. For example, Google employees are listed here +# but not in AUTHORS, because Google holds the copyright. +# +# The submission process automatically checks to make sure +# that people submitting code are listed in this file (by email address). +# +# Names should be added to this file only after verifying that +# the individual or the individual's organization has agreed to +# the appropriate Contributor License Agreement, found here: +# +# https://cla.developers.google.com/about/google-individual +# https://cla.developers.google.com/about/google-corporate +# +# The CLA can be filled out on the web: +# +# https://cla.developers.google.com/ +# +# When adding J Random Contributor's name to this file, +# either J's name or J's organization's name should be +# added to the AUTHORS file, depending on whether the +# individual or corporate CLA was used. + +# Names should be added to this file like so: +# Name +# +# An entry with two email addresses specifies that the +# first address should be used in the submit logs and +# that the second address should be recognized as the +# same person when interacting with Rietveld. + +# Please keep the list sorted. + +Alain Vongsouvanhalainv +Andrew Gerrand +Brad Fitzpatrick +Eric Koleda +Francesc Campoy +Garrick Evans +Glenn Lewis +Ivan Krasin +Jason Hall +Johan Euphrosine +Kostik Shtoyk +Kunpei Sakai +Matthew Whisenhunt +Michael McGreevy +Nick Craig-Wood +Robbie Trencheny +Ross Light +Sarah Adams +Scott Van Woudenberg +Takashi Matsuo diff --git a/vendor/google.golang.org/api/LICENSE b/vendor/google.golang.org/api/LICENSE new file mode 100644 index 00000000..263aa7a0 --- /dev/null +++ b/vendor/google.golang.org/api/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2011 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/google.golang.org/api/admin/directory/v1/admin-api.json b/vendor/google.golang.org/api/admin/directory/v1/admin-api.json new file mode 100644 index 00000000..67c5393d --- /dev/null +++ b/vendor/google.golang.org/api/admin/directory/v1/admin-api.json @@ -0,0 +1,7034 @@ +{ + "auth": { + "oauth2": { + "scopes": { + "https://www.googleapis.com/auth/admin.directory.customer": { + "description": "View and manage customer related information" + }, + "https://www.googleapis.com/auth/admin.directory.customer.readonly": { + "description": "View customer related information" + }, + "https://www.googleapis.com/auth/admin.directory.device.chromeos": { + "description": "View and manage your Chrome OS devices' metadata" + }, + "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly": { + "description": "View your Chrome OS devices' metadata" + }, + "https://www.googleapis.com/auth/admin.directory.device.mobile": { + "description": "View and manage your mobile devices' metadata" + }, + "https://www.googleapis.com/auth/admin.directory.device.mobile.action": { + "description": "Manage your mobile devices by performing administrative tasks" + }, + "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly": { + "description": "View your mobile devices' metadata" + }, + "https://www.googleapis.com/auth/admin.directory.domain": { + "description": "View and manage the provisioning of domains for your customers" + }, + "https://www.googleapis.com/auth/admin.directory.domain.readonly": { + "description": "View domains related to your customers" + }, + "https://www.googleapis.com/auth/admin.directory.group": { + "description": "View and manage the provisioning of groups on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.group.member": { + "description": "View and manage group subscriptions on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.group.member.readonly": { + "description": "View group subscriptions on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.group.readonly": { + "description": "View groups on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.notifications": { + "description": "View and manage notifications received on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.orgunit": { + "description": "View and manage organization units on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.orgunit.readonly": { + "description": "View organization units on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.resource.calendar": { + "description": "View and manage the provisioning of calendar resources on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly": { + "description": "View calendar resources on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.rolemanagement": { + "description": "Manage delegated admin roles for your domain" + }, + "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly": { + "description": "View delegated admin roles for your domain" + }, + "https://www.googleapis.com/auth/admin.directory.user": { + "description": "View and manage the provisioning of users on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.user.alias": { + "description": "View and manage user aliases on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.user.alias.readonly": { + "description": "View user aliases on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.user.readonly": { + "description": "View users on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.user.security": { + "description": "Manage data access permissions for users on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.userschema": { + "description": "View and manage the provisioning of user schemas on your domain" + }, + "https://www.googleapis.com/auth/admin.directory.userschema.readonly": { + "description": "View user schemas on your domain" + } + } + } + }, + "basePath": "/admin/directory/v1/", + "baseUrl": "https://www.googleapis.com/admin/directory/v1/", + "batchPath": "batch/admin/directory_v1", + "canonicalName": "directory", + "description": "Manages enterprise resources such as users and groups, administrative notifications, security features, and more.", + "discoveryVersion": "v1", + "documentationLink": "https://developers.google.com/admin-sdk/directory/", + "etag": "\"9eZ1uxVRThTDhLJCZHhqs3eQWz4/5HuD5_WBYDvRWcfO5I5hjCFh4pY\"", + "icons": { + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" + }, + "id": "admin:directory_v1", + "kind": "discovery#restDescription", + "name": "admin", + "ownerDomain": "google.com", + "ownerName": "Google", + "packagePath": "admin", + "parameters": { + "alt": { + "default": "json", + "description": "Data format for the response.", + "enum": [ + "json" + ], + "enumDescriptions": [ + "Responses with Content-Type of application/json" + ], + "location": "query", + "type": "string" + }, + "fields": { + "description": "Selector specifying which fields to include in a partial response.", + "location": "query", + "type": "string" + }, + "key": { + "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", + "location": "query", + "type": "string" + }, + "oauth_token": { + "description": "OAuth 2.0 token for the current user.", + "location": "query", + "type": "string" + }, + "prettyPrint": { + "default": "true", + "description": "Returns response with indentations and line breaks.", + "location": "query", + "type": "boolean" + }, + "quotaUser": { + "description": "An opaque string that represents a user for quota purposes. Must not exceed 40 characters.", + "location": "query", + "type": "string" + }, + "userIp": { + "description": "Deprecated. Please use quotaUser instead.", + "location": "query", + "type": "string" + } + }, + "protocol": "rest", + "resources": { + "asps": { + "methods": { + "delete": { + "description": "Delete an ASP issued by a user.", + "httpMethod": "DELETE", + "id": "directory.asps.delete", + "parameterOrder": [ + "userKey", + "codeId" + ], + "parameters": { + "codeId": { + "description": "The unique ID of the ASP to be deleted.", + "format": "int32", + "location": "path", + "required": true, + "type": "integer" + }, + "userKey": { + "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/asps/{codeId}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user.security" + ] + }, + "get": { + "description": "Get information about an ASP issued by a user.", + "httpMethod": "GET", + "id": "directory.asps.get", + "parameterOrder": [ + "userKey", + "codeId" + ], + "parameters": { + "codeId": { + "description": "The unique ID of the ASP.", + "format": "int32", + "location": "path", + "required": true, + "type": "integer" + }, + "userKey": { + "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/asps/{codeId}", + "response": { + "$ref": "Asp" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user.security" + ] + }, + "list": { + "description": "List the ASPs issued by a user.", + "httpMethod": "GET", + "id": "directory.asps.list", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/asps", + "response": { + "$ref": "Asps" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user.security" + ] + } + } + }, + "channels": { + "methods": { + "stop": { + "description": "Stop watching resources through this channel", + "httpMethod": "POST", + "id": "admin.channels.stop", + "path": "/admin/directory_v1/channels/stop", + "request": { + "$ref": "Channel", + "parameterName": "resource" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user", + "https://www.googleapis.com/auth/admin.directory.user.alias", + "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", + "https://www.googleapis.com/auth/admin.directory.user.readonly" + ] + } + } + }, + "chromeosdevices": { + "methods": { + "action": { + "description": "Take action on Chrome OS Device", + "httpMethod": "POST", + "id": "directory.chromeosdevices.action", + "parameterOrder": [ + "customerId", + "resourceId" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "resourceId": { + "description": "Immutable ID of Chrome OS Device", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/devices/chromeos/{resourceId}/action", + "request": { + "$ref": "ChromeOsDeviceAction" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.device.chromeos" + ] + }, + "get": { + "description": "Retrieve Chrome OS Device", + "httpMethod": "GET", + "id": "directory.chromeosdevices.get", + "parameterOrder": [ + "customerId", + "deviceId" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "deviceId": { + "description": "Immutable ID of Chrome OS Device", + "location": "path", + "required": true, + "type": "string" + }, + "projection": { + "description": "Restrict information returned to a set of selected fields.", + "enum": [ + "BASIC", + "FULL" + ], + "enumDescriptions": [ + "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", + "Includes all metadata fields" + ], + "location": "query", + "type": "string" + } + }, + "path": "customer/{customerId}/devices/chromeos/{deviceId}", + "response": { + "$ref": "ChromeOsDevice" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.device.chromeos", + "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly" + ] + }, + "list": { + "description": "Retrieve all Chrome OS Devices of a customer (paginated)", + "httpMethod": "GET", + "id": "directory.chromeosdevices.list", + "parameterOrder": [ + "customerId" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "maxResults": { + "default": "100", + "description": "Maximum number of results to return. Max allowed value is 200.", + "format": "int32", + "location": "query", + "minimum": "1", + "type": "integer" + }, + "orderBy": { + "description": "Column to use for sorting results", + "enum": [ + "annotatedLocation", + "annotatedUser", + "lastSync", + "notes", + "serialNumber", + "status", + "supportEndDate" + ], + "enumDescriptions": [ + "Chromebook location as annotated by the administrator.", + "Chromebook user as annotated by administrator.", + "Chromebook last sync.", + "Chromebook notes as annotated by the administrator.", + "Chromebook Serial Number.", + "Chromebook status.", + "Chromebook support end date." + ], + "location": "query", + "type": "string" + }, + "orgUnitPath": { + "description": "Full path of the organizational unit or its ID", + "location": "query", + "type": "string" + }, + "pageToken": { + "description": "Token to specify next page in the list", + "location": "query", + "type": "string" + }, + "projection": { + "description": "Restrict information returned to a set of selected fields.", + "enum": [ + "BASIC", + "FULL" + ], + "enumDescriptions": [ + "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", + "Includes all metadata fields" + ], + "location": "query", + "type": "string" + }, + "query": { + "description": "Search string in the format given at http://support.google.com/chromeos/a/bin/answer.py?answer=1698333", + "location": "query", + "type": "string" + }, + "sortOrder": { + "description": "Whether to return results in ascending or descending order. Only of use when orderBy is also used", + "enum": [ + "ASCENDING", + "DESCENDING" + ], + "enumDescriptions": [ + "Ascending order.", + "Descending order." + ], + "location": "query", + "type": "string" + } + }, + "path": "customer/{customerId}/devices/chromeos", + "response": { + "$ref": "ChromeOsDevices" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.device.chromeos", + "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly" + ] + }, + "moveDevicesToOu": { + "description": "Move or insert multiple Chrome OS Devices to organizational unit", + "httpMethod": "POST", + "id": "directory.chromeosdevices.moveDevicesToOu", + "parameterOrder": [ + "customerId", + "orgUnitPath" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "orgUnitPath": { + "description": "Full path of the target organizational unit or its ID", + "location": "query", + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/devices/chromeos/moveDevicesToOu", + "request": { + "$ref": "ChromeOsMoveDevicesToOu" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.device.chromeos" + ] + }, + "patch": { + "description": "Update Chrome OS Device. This method supports patch semantics.", + "httpMethod": "PATCH", + "id": "directory.chromeosdevices.patch", + "parameterOrder": [ + "customerId", + "deviceId" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "deviceId": { + "description": "Immutable ID of Chrome OS Device", + "location": "path", + "required": true, + "type": "string" + }, + "projection": { + "description": "Restrict information returned to a set of selected fields.", + "enum": [ + "BASIC", + "FULL" + ], + "enumDescriptions": [ + "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", + "Includes all metadata fields" + ], + "location": "query", + "type": "string" + } + }, + "path": "customer/{customerId}/devices/chromeos/{deviceId}", + "request": { + "$ref": "ChromeOsDevice" + }, + "response": { + "$ref": "ChromeOsDevice" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.device.chromeos" + ] + }, + "update": { + "description": "Update Chrome OS Device", + "httpMethod": "PUT", + "id": "directory.chromeosdevices.update", + "parameterOrder": [ + "customerId", + "deviceId" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "deviceId": { + "description": "Immutable ID of Chrome OS Device", + "location": "path", + "required": true, + "type": "string" + }, + "projection": { + "description": "Restrict information returned to a set of selected fields.", + "enum": [ + "BASIC", + "FULL" + ], + "enumDescriptions": [ + "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", + "Includes all metadata fields" + ], + "location": "query", + "type": "string" + } + }, + "path": "customer/{customerId}/devices/chromeos/{deviceId}", + "request": { + "$ref": "ChromeOsDevice" + }, + "response": { + "$ref": "ChromeOsDevice" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.device.chromeos" + ] + } + } + }, + "customers": { + "methods": { + "get": { + "description": "Retrieves a customer.", + "httpMethod": "GET", + "id": "directory.customers.get", + "parameterOrder": [ + "customerKey" + ], + "parameters": { + "customerKey": { + "description": "Id of the customer to be retrieved", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customers/{customerKey}", + "response": { + "$ref": "Customer" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.customer", + "https://www.googleapis.com/auth/admin.directory.customer.readonly" + ] + }, + "patch": { + "description": "Updates a customer. This method supports patch semantics.", + "httpMethod": "PATCH", + "id": "directory.customers.patch", + "parameterOrder": [ + "customerKey" + ], + "parameters": { + "customerKey": { + "description": "Id of the customer to be updated", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customers/{customerKey}", + "request": { + "$ref": "Customer" + }, + "response": { + "$ref": "Customer" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.customer" + ] + }, + "update": { + "description": "Updates a customer.", + "httpMethod": "PUT", + "id": "directory.customers.update", + "parameterOrder": [ + "customerKey" + ], + "parameters": { + "customerKey": { + "description": "Id of the customer to be updated", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customers/{customerKey}", + "request": { + "$ref": "Customer" + }, + "response": { + "$ref": "Customer" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.customer" + ] + } + } + }, + "domainAliases": { + "methods": { + "delete": { + "description": "Deletes a Domain Alias of the customer.", + "httpMethod": "DELETE", + "id": "directory.domainAliases.delete", + "parameterOrder": [ + "customer", + "domainAliasName" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "domainAliasName": { + "description": "Name of domain alias to be retrieved.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/domainaliases/{domainAliasName}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.domain" + ] + }, + "get": { + "description": "Retrieves a domain alias of the customer.", + "httpMethod": "GET", + "id": "directory.domainAliases.get", + "parameterOrder": [ + "customer", + "domainAliasName" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "domainAliasName": { + "description": "Name of domain alias to be retrieved.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/domainaliases/{domainAliasName}", + "response": { + "$ref": "DomainAlias" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.domain", + "https://www.googleapis.com/auth/admin.directory.domain.readonly" + ] + }, + "insert": { + "description": "Inserts a Domain alias of the customer.", + "httpMethod": "POST", + "id": "directory.domainAliases.insert", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/domainaliases", + "request": { + "$ref": "DomainAlias" + }, + "response": { + "$ref": "DomainAlias" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.domain" + ] + }, + "list": { + "description": "Lists the domain aliases of the customer.", + "httpMethod": "GET", + "id": "directory.domainAliases.list", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "parentDomainName": { + "description": "Name of the parent domain for which domain aliases are to be fetched.", + "location": "query", + "type": "string" + } + }, + "path": "customer/{customer}/domainaliases", + "response": { + "$ref": "DomainAliases" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.domain", + "https://www.googleapis.com/auth/admin.directory.domain.readonly" + ] + } + } + }, + "domains": { + "methods": { + "delete": { + "description": "Deletes a domain of the customer.", + "httpMethod": "DELETE", + "id": "directory.domains.delete", + "parameterOrder": [ + "customer", + "domainName" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "domainName": { + "description": "Name of domain to be deleted", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/domains/{domainName}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.domain" + ] + }, + "get": { + "description": "Retrieves a domain of the customer.", + "httpMethod": "GET", + "id": "directory.domains.get", + "parameterOrder": [ + "customer", + "domainName" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "domainName": { + "description": "Name of domain to be retrieved", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/domains/{domainName}", + "response": { + "$ref": "Domains" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.domain", + "https://www.googleapis.com/auth/admin.directory.domain.readonly" + ] + }, + "insert": { + "description": "Inserts a domain of the customer.", + "httpMethod": "POST", + "id": "directory.domains.insert", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/domains", + "request": { + "$ref": "Domains" + }, + "response": { + "$ref": "Domains" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.domain" + ] + }, + "list": { + "description": "Lists the domains of the customer.", + "httpMethod": "GET", + "id": "directory.domains.list", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/domains", + "response": { + "$ref": "Domains2" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.domain", + "https://www.googleapis.com/auth/admin.directory.domain.readonly" + ] + } + } + }, + "groups": { + "methods": { + "delete": { + "description": "Delete Group", + "httpMethod": "DELETE", + "id": "directory.groups.delete", + "parameterOrder": [ + "groupKey" + ], + "parameters": { + "groupKey": { + "description": "Email or immutable ID of the group", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "groups/{groupKey}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group" + ] + }, + "get": { + "description": "Retrieve Group", + "httpMethod": "GET", + "id": "directory.groups.get", + "parameterOrder": [ + "groupKey" + ], + "parameters": { + "groupKey": { + "description": "Email or immutable ID of the group", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "groups/{groupKey}", + "response": { + "$ref": "Group" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group", + "https://www.googleapis.com/auth/admin.directory.group.readonly" + ] + }, + "insert": { + "description": "Create Group", + "httpMethod": "POST", + "id": "directory.groups.insert", + "path": "groups", + "request": { + "$ref": "Group" + }, + "response": { + "$ref": "Group" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group" + ] + }, + "list": { + "description": "Retrieve all groups of a domain or of a user given a userKey (paginated)", + "httpMethod": "GET", + "id": "directory.groups.list", + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account. In case of multi-domain, to fetch all groups for a customer, fill this field instead of domain.", + "location": "query", + "type": "string" + }, + "domain": { + "description": "Name of the domain. Fill this field to get groups from only this domain. To return all groups in a multi-domain fill customer field instead.", + "location": "query", + "type": "string" + }, + "maxResults": { + "default": "200", + "description": "Maximum number of results to return. Max allowed value is 200.", + "format": "int32", + "location": "query", + "minimum": "1", + "type": "integer" + }, + "orderBy": { + "description": "Column to use for sorting results", + "enum": [ + "email" + ], + "enumDescriptions": [ + "Email of the group." + ], + "location": "query", + "type": "string" + }, + "pageToken": { + "description": "Token to specify next page in the list", + "location": "query", + "type": "string" + }, + "query": { + "description": "Query string search. Should be of the form \"\". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-groups", + "location": "query", + "type": "string" + }, + "sortOrder": { + "description": "Whether to return results in ascending or descending order. Only of use when orderBy is also used", + "enum": [ + "ASCENDING", + "DESCENDING" + ], + "enumDescriptions": [ + "Ascending order.", + "Descending order." + ], + "location": "query", + "type": "string" + }, + "userKey": { + "description": "Email or immutable ID of the user if only those groups are to be listed, the given user is a member of. If it's an ID, it should match with the ID of the user object.", + "location": "query", + "type": "string" + } + }, + "path": "groups", + "response": { + "$ref": "Groups" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group", + "https://www.googleapis.com/auth/admin.directory.group.readonly" + ] + }, + "patch": { + "description": "Update Group. This method supports patch semantics.", + "httpMethod": "PATCH", + "id": "directory.groups.patch", + "parameterOrder": [ + "groupKey" + ], + "parameters": { + "groupKey": { + "description": "Email or immutable ID of the group. If ID, it should match with id of group object", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "groups/{groupKey}", + "request": { + "$ref": "Group" + }, + "response": { + "$ref": "Group" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group" + ] + }, + "update": { + "description": "Update Group", + "httpMethod": "PUT", + "id": "directory.groups.update", + "parameterOrder": [ + "groupKey" + ], + "parameters": { + "groupKey": { + "description": "Email or immutable ID of the group. If ID, it should match with id of group object", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "groups/{groupKey}", + "request": { + "$ref": "Group" + }, + "response": { + "$ref": "Group" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group" + ] + } + }, + "resources": { + "aliases": { + "methods": { + "delete": { + "description": "Remove a alias for the group", + "httpMethod": "DELETE", + "id": "directory.groups.aliases.delete", + "parameterOrder": [ + "groupKey", + "alias" + ], + "parameters": { + "alias": { + "description": "The alias to be removed", + "location": "path", + "required": true, + "type": "string" + }, + "groupKey": { + "description": "Email or immutable ID of the group", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "groups/{groupKey}/aliases/{alias}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group" + ] + }, + "insert": { + "description": "Add a alias for the group", + "httpMethod": "POST", + "id": "directory.groups.aliases.insert", + "parameterOrder": [ + "groupKey" + ], + "parameters": { + "groupKey": { + "description": "Email or immutable ID of the group", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "groups/{groupKey}/aliases", + "request": { + "$ref": "Alias" + }, + "response": { + "$ref": "Alias" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group" + ] + }, + "list": { + "description": "List all aliases for a group", + "httpMethod": "GET", + "id": "directory.groups.aliases.list", + "parameterOrder": [ + "groupKey" + ], + "parameters": { + "groupKey": { + "description": "Email or immutable ID of the group", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "groups/{groupKey}/aliases", + "response": { + "$ref": "Aliases" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group", + "https://www.googleapis.com/auth/admin.directory.group.readonly" + ], + "supportsSubscription": true + } + } + } + } + }, + "members": { + "methods": { + "delete": { + "description": "Remove membership.", + "httpMethod": "DELETE", + "id": "directory.members.delete", + "parameterOrder": [ + "groupKey", + "memberKey" + ], + "parameters": { + "groupKey": { + "description": "Email or immutable ID of the group", + "location": "path", + "required": true, + "type": "string" + }, + "memberKey": { + "description": "Email or immutable ID of the member", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "groups/{groupKey}/members/{memberKey}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group", + "https://www.googleapis.com/auth/admin.directory.group.member" + ] + }, + "get": { + "description": "Retrieve Group Member", + "httpMethod": "GET", + "id": "directory.members.get", + "parameterOrder": [ + "groupKey", + "memberKey" + ], + "parameters": { + "groupKey": { + "description": "Email or immutable ID of the group", + "location": "path", + "required": true, + "type": "string" + }, + "memberKey": { + "description": "Email or immutable ID of the member", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "groups/{groupKey}/members/{memberKey}", + "response": { + "$ref": "Member" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group", + "https://www.googleapis.com/auth/admin.directory.group.member", + "https://www.googleapis.com/auth/admin.directory.group.member.readonly", + "https://www.googleapis.com/auth/admin.directory.group.readonly" + ] + }, + "hasMember": { + "description": "Checks whether the given user is a member of the group. Membership can be direct or nested.", + "httpMethod": "GET", + "id": "directory.members.hasMember", + "parameterOrder": [ + "groupKey", + "memberKey" + ], + "parameters": { + "groupKey": { + "description": "Identifies the group in the API request. The value can be the group's email address, group alias, or the unique group ID.", + "location": "path", + "required": true, + "type": "string" + }, + "memberKey": { + "description": "Identifies the user member in the API request. The value can be the user's primary email address, alias, or unique ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "groups/{groupKey}/hasMember/{memberKey}", + "response": { + "$ref": "MembersHasMember" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group", + "https://www.googleapis.com/auth/admin.directory.group.member", + "https://www.googleapis.com/auth/admin.directory.group.member.readonly", + "https://www.googleapis.com/auth/admin.directory.group.readonly" + ] + }, + "insert": { + "description": "Add user to the specified group.", + "httpMethod": "POST", + "id": "directory.members.insert", + "parameterOrder": [ + "groupKey" + ], + "parameters": { + "groupKey": { + "description": "Email or immutable ID of the group", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "groups/{groupKey}/members", + "request": { + "$ref": "Member" + }, + "response": { + "$ref": "Member" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group", + "https://www.googleapis.com/auth/admin.directory.group.member" + ] + }, + "list": { + "description": "Retrieve all members in a group (paginated)", + "httpMethod": "GET", + "id": "directory.members.list", + "parameterOrder": [ + "groupKey" + ], + "parameters": { + "groupKey": { + "description": "Email or immutable ID of the group", + "location": "path", + "required": true, + "type": "string" + }, + "includeDerivedMembership": { + "description": "Whether to list indirect memberships. Default: false.", + "location": "query", + "type": "boolean" + }, + "maxResults": { + "default": "200", + "description": "Maximum number of results to return. Max allowed value is 200.", + "format": "int32", + "location": "query", + "minimum": "1", + "type": "integer" + }, + "pageToken": { + "description": "Token to specify next page in the list", + "location": "query", + "type": "string" + }, + "roles": { + "description": "Comma separated role values to filter list results on.", + "location": "query", + "type": "string" + } + }, + "path": "groups/{groupKey}/members", + "response": { + "$ref": "Members" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group", + "https://www.googleapis.com/auth/admin.directory.group.member", + "https://www.googleapis.com/auth/admin.directory.group.member.readonly", + "https://www.googleapis.com/auth/admin.directory.group.readonly" + ] + }, + "patch": { + "description": "Update membership of a user in the specified group. This method supports patch semantics.", + "httpMethod": "PATCH", + "id": "directory.members.patch", + "parameterOrder": [ + "groupKey", + "memberKey" + ], + "parameters": { + "groupKey": { + "description": "Email or immutable ID of the group. If ID, it should match with id of group object", + "location": "path", + "required": true, + "type": "string" + }, + "memberKey": { + "description": "Email or immutable ID of the user. If ID, it should match with id of member object", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "groups/{groupKey}/members/{memberKey}", + "request": { + "$ref": "Member" + }, + "response": { + "$ref": "Member" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group", + "https://www.googleapis.com/auth/admin.directory.group.member" + ] + }, + "update": { + "description": "Update membership of a user in the specified group.", + "httpMethod": "PUT", + "id": "directory.members.update", + "parameterOrder": [ + "groupKey", + "memberKey" + ], + "parameters": { + "groupKey": { + "description": "Email or immutable ID of the group. If ID, it should match with id of group object", + "location": "path", + "required": true, + "type": "string" + }, + "memberKey": { + "description": "Email or immutable ID of the user. If ID, it should match with id of member object", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "groups/{groupKey}/members/{memberKey}", + "request": { + "$ref": "Member" + }, + "response": { + "$ref": "Member" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.group", + "https://www.googleapis.com/auth/admin.directory.group.member" + ] + } + } + }, + "mobiledevices": { + "methods": { + "action": { + "description": "Take action on Mobile Device", + "httpMethod": "POST", + "id": "directory.mobiledevices.action", + "parameterOrder": [ + "customerId", + "resourceId" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "resourceId": { + "description": "Immutable ID of Mobile Device", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/devices/mobile/{resourceId}/action", + "request": { + "$ref": "MobileDeviceAction" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.device.mobile", + "https://www.googleapis.com/auth/admin.directory.device.mobile.action" + ] + }, + "delete": { + "description": "Delete Mobile Device", + "httpMethod": "DELETE", + "id": "directory.mobiledevices.delete", + "parameterOrder": [ + "customerId", + "resourceId" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "resourceId": { + "description": "Immutable ID of Mobile Device", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/devices/mobile/{resourceId}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.device.mobile" + ] + }, + "get": { + "description": "Retrieve Mobile Device", + "httpMethod": "GET", + "id": "directory.mobiledevices.get", + "parameterOrder": [ + "customerId", + "resourceId" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "projection": { + "description": "Restrict information returned to a set of selected fields.", + "enum": [ + "BASIC", + "FULL" + ], + "enumDescriptions": [ + "Includes only the basic metadata fields (e.g., deviceId, model, status, type, and status)", + "Includes all metadata fields" + ], + "location": "query", + "type": "string" + }, + "resourceId": { + "description": "Immutable ID of Mobile Device", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/devices/mobile/{resourceId}", + "response": { + "$ref": "MobileDevice" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.device.mobile", + "https://www.googleapis.com/auth/admin.directory.device.mobile.action", + "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly" + ] + }, + "list": { + "description": "Retrieve all Mobile Devices of a customer (paginated)", + "httpMethod": "GET", + "id": "directory.mobiledevices.list", + "parameterOrder": [ + "customerId" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "maxResults": { + "default": "100", + "description": "Maximum number of results to return. Max allowed value is 100.", + "format": "int32", + "location": "query", + "minimum": "1", + "type": "integer" + }, + "orderBy": { + "description": "Column to use for sorting results", + "enum": [ + "deviceId", + "email", + "lastSync", + "model", + "name", + "os", + "status", + "type" + ], + "enumDescriptions": [ + "Mobile Device serial number.", + "Owner user email.", + "Last policy settings sync date time of the device.", + "Mobile Device model.", + "Owner user name.", + "Mobile operating system.", + "Status of the device.", + "Type of the device." + ], + "location": "query", + "type": "string" + }, + "pageToken": { + "description": "Token to specify next page in the list", + "location": "query", + "type": "string" + }, + "projection": { + "description": "Restrict information returned to a set of selected fields.", + "enum": [ + "BASIC", + "FULL" + ], + "enumDescriptions": [ + "Includes only the basic metadata fields (e.g., deviceId, model, status, type, and status)", + "Includes all metadata fields" + ], + "location": "query", + "type": "string" + }, + "query": { + "description": "Search string in the format given at http://support.google.com/a/bin/answer.py?answer=1408863#search", + "location": "query", + "type": "string" + }, + "sortOrder": { + "description": "Whether to return results in ascending or descending order. Only of use when orderBy is also used", + "enum": [ + "ASCENDING", + "DESCENDING" + ], + "enumDescriptions": [ + "Ascending order.", + "Descending order." + ], + "location": "query", + "type": "string" + } + }, + "path": "customer/{customerId}/devices/mobile", + "response": { + "$ref": "MobileDevices" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.device.mobile", + "https://www.googleapis.com/auth/admin.directory.device.mobile.action", + "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly" + ] + } + } + }, + "notifications": { + "methods": { + "delete": { + "description": "Deletes a notification", + "httpMethod": "DELETE", + "id": "directory.notifications.delete", + "parameterOrder": [ + "customer", + "notificationId" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account. The customerId is also returned as part of the Users resource.", + "location": "path", + "required": true, + "type": "string" + }, + "notificationId": { + "description": "The unique ID of the notification.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/notifications/{notificationId}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.notifications" + ] + }, + "get": { + "description": "Retrieves a notification.", + "httpMethod": "GET", + "id": "directory.notifications.get", + "parameterOrder": [ + "customer", + "notificationId" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account. The customerId is also returned as part of the Users resource.", + "location": "path", + "required": true, + "type": "string" + }, + "notificationId": { + "description": "The unique ID of the notification.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/notifications/{notificationId}", + "response": { + "$ref": "Notification" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.notifications" + ] + }, + "list": { + "description": "Retrieves a list of notifications.", + "httpMethod": "GET", + "id": "directory.notifications.list", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "language": { + "description": "The ISO 639-1 code of the language notifications are returned in. The default is English (en).", + "location": "query", + "type": "string" + }, + "maxResults": { + "description": "Maximum number of notifications to return per page. The default is 100.", + "format": "uint32", + "location": "query", + "type": "integer" + }, + "pageToken": { + "description": "The token to specify the page of results to retrieve.", + "location": "query", + "type": "string" + } + }, + "path": "customer/{customer}/notifications", + "response": { + "$ref": "Notifications" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.notifications" + ] + }, + "patch": { + "description": "Updates a notification. This method supports patch semantics.", + "httpMethod": "PATCH", + "id": "directory.notifications.patch", + "parameterOrder": [ + "customer", + "notificationId" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "notificationId": { + "description": "The unique ID of the notification.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/notifications/{notificationId}", + "request": { + "$ref": "Notification" + }, + "response": { + "$ref": "Notification" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.notifications" + ] + }, + "update": { + "description": "Updates a notification.", + "httpMethod": "PUT", + "id": "directory.notifications.update", + "parameterOrder": [ + "customer", + "notificationId" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "notificationId": { + "description": "The unique ID of the notification.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/notifications/{notificationId}", + "request": { + "$ref": "Notification" + }, + "response": { + "$ref": "Notification" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.notifications" + ] + } + } + }, + "orgunits": { + "methods": { + "delete": { + "description": "Remove organizational unit", + "httpMethod": "DELETE", + "id": "directory.orgunits.delete", + "parameterOrder": [ + "customerId", + "orgUnitPath" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "orgUnitPath": { + "description": "Full path of the organizational unit or its ID", + "location": "path", + "repeated": true, + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/orgunits{/orgUnitPath*}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.orgunit" + ] + }, + "get": { + "description": "Retrieve organizational unit", + "httpMethod": "GET", + "id": "directory.orgunits.get", + "parameterOrder": [ + "customerId", + "orgUnitPath" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "orgUnitPath": { + "description": "Full path of the organizational unit or its ID", + "location": "path", + "repeated": true, + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/orgunits{/orgUnitPath*}", + "response": { + "$ref": "OrgUnit" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.orgunit", + "https://www.googleapis.com/auth/admin.directory.orgunit.readonly" + ] + }, + "insert": { + "description": "Add organizational unit", + "httpMethod": "POST", + "id": "directory.orgunits.insert", + "parameterOrder": [ + "customerId" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/orgunits", + "request": { + "$ref": "OrgUnit" + }, + "response": { + "$ref": "OrgUnit" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.orgunit" + ] + }, + "list": { + "description": "Retrieve all organizational units", + "httpMethod": "GET", + "id": "directory.orgunits.list", + "parameterOrder": [ + "customerId" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "orgUnitPath": { + "default": "", + "description": "the URL-encoded organizational unit's path or its ID", + "location": "query", + "type": "string" + }, + "type": { + "description": "Whether to return all sub-organizations or just immediate children", + "enum": [ + "all", + "children" + ], + "enumDescriptions": [ + "All sub-organizational units.", + "Immediate children only (default)." + ], + "location": "query", + "type": "string" + } + }, + "path": "customer/{customerId}/orgunits", + "response": { + "$ref": "OrgUnits" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.orgunit", + "https://www.googleapis.com/auth/admin.directory.orgunit.readonly" + ] + }, + "patch": { + "description": "Update organizational unit. This method supports patch semantics.", + "httpMethod": "PATCH", + "id": "directory.orgunits.patch", + "parameterOrder": [ + "customerId", + "orgUnitPath" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "orgUnitPath": { + "description": "Full path of the organizational unit or its ID", + "location": "path", + "repeated": true, + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/orgunits{/orgUnitPath*}", + "request": { + "$ref": "OrgUnit" + }, + "response": { + "$ref": "OrgUnit" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.orgunit" + ] + }, + "update": { + "description": "Update organizational unit", + "httpMethod": "PUT", + "id": "directory.orgunits.update", + "parameterOrder": [ + "customerId", + "orgUnitPath" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "orgUnitPath": { + "description": "Full path of the organizational unit or its ID", + "location": "path", + "repeated": true, + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/orgunits{/orgUnitPath*}", + "request": { + "$ref": "OrgUnit" + }, + "response": { + "$ref": "OrgUnit" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.orgunit" + ] + } + } + }, + "privileges": { + "methods": { + "list": { + "description": "Retrieves a paginated list of all privileges for a customer.", + "httpMethod": "GET", + "id": "directory.privileges.list", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/roles/ALL/privileges", + "response": { + "$ref": "Privileges" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.rolemanagement", + "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" + ] + } + } + }, + "resolvedAppAccessSettings": { + "methods": { + "GetSettings": { + "description": "Retrieves resolved app access settings of the logged in user.", + "httpMethod": "GET", + "id": "directory.resolvedAppAccessSettings.GetSettings", + "path": "resolvedappaccesssettings", + "response": { + "$ref": "AppAccessCollections" + } + }, + "ListTrustedApps": { + "description": "Retrieves the list of apps trusted by the admin of the logged in user.", + "httpMethod": "GET", + "id": "directory.resolvedAppAccessSettings.ListTrustedApps", + "path": "trustedapps", + "response": { + "$ref": "TrustedApps" + } + } + } + }, + "resources": { + "resources": { + "buildings": { + "methods": { + "delete": { + "description": "Deletes a building.", + "httpMethod": "DELETE", + "id": "directory.resources.buildings.delete", + "parameterOrder": [ + "customer", + "buildingId" + ], + "parameters": { + "buildingId": { + "description": "The ID of the building to delete.", + "location": "path", + "required": true, + "type": "string" + }, + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/buildings/{buildingId}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar" + ] + }, + "get": { + "description": "Retrieves a building.", + "httpMethod": "GET", + "id": "directory.resources.buildings.get", + "parameterOrder": [ + "customer", + "buildingId" + ], + "parameters": { + "buildingId": { + "description": "The unique ID of the building to retrieve.", + "location": "path", + "required": true, + "type": "string" + }, + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/buildings/{buildingId}", + "response": { + "$ref": "Building" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar", + "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" + ] + }, + "insert": { + "description": "Inserts a building.", + "httpMethod": "POST", + "id": "directory.resources.buildings.insert", + "parameterOrder": [ + "customer" + ], + "parameters": { + "coordinatesSource": { + "default": "SOURCE_UNSPECIFIED", + "description": "Source from which Building.coordinates are derived.", + "enum": [ + "CLIENT_SPECIFIED", + "RESOLVED_FROM_ADDRESS", + "SOURCE_UNSPECIFIED" + ], + "enumDescriptions": [ + "Building.coordinates are set to the coordinates included in the request.", + "Building.coordinates are automatically populated based on the postal address.", + "Defaults to RESOLVED_FROM_ADDRESS if postal address is provided. Otherwise, defaults to CLIENT_SPECIFIED if coordinates are provided." + ], + "location": "query", + "type": "string" + }, + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/buildings", + "request": { + "$ref": "Building" + }, + "response": { + "$ref": "Building" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar" + ] + }, + "list": { + "description": "Retrieves a list of buildings for an account.", + "httpMethod": "GET", + "id": "directory.resources.buildings.list", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + }, + "maxResults": { + "description": "Maximum number of results to return.", + "format": "int32", + "location": "query", + "maximum": "500", + "minimum": "1", + "type": "integer" + }, + "pageToken": { + "description": "Token to specify the next page in the list.", + "location": "query", + "type": "string" + } + }, + "path": "customer/{customer}/resources/buildings", + "response": { + "$ref": "Buildings" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar", + "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" + ] + }, + "patch": { + "description": "Updates a building. This method supports patch semantics.", + "httpMethod": "PATCH", + "id": "directory.resources.buildings.patch", + "parameterOrder": [ + "customer", + "buildingId" + ], + "parameters": { + "buildingId": { + "description": "The ID of the building to update.", + "location": "path", + "required": true, + "type": "string" + }, + "coordinatesSource": { + "default": "SOURCE_UNSPECIFIED", + "description": "Source from which Building.coordinates are derived.", + "enum": [ + "CLIENT_SPECIFIED", + "RESOLVED_FROM_ADDRESS", + "SOURCE_UNSPECIFIED" + ], + "enumDescriptions": [ + "Building.coordinates are set to the coordinates included in the request.", + "Building.coordinates are automatically populated based on the postal address.", + "Defaults to RESOLVED_FROM_ADDRESS if postal address is provided. Otherwise, defaults to CLIENT_SPECIFIED if coordinates are provided." + ], + "location": "query", + "type": "string" + }, + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/buildings/{buildingId}", + "request": { + "$ref": "Building" + }, + "response": { + "$ref": "Building" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar" + ] + }, + "update": { + "description": "Updates a building.", + "httpMethod": "PUT", + "id": "directory.resources.buildings.update", + "parameterOrder": [ + "customer", + "buildingId" + ], + "parameters": { + "buildingId": { + "description": "The ID of the building to update.", + "location": "path", + "required": true, + "type": "string" + }, + "coordinatesSource": { + "default": "SOURCE_UNSPECIFIED", + "description": "Source from which Building.coordinates are derived.", + "enum": [ + "CLIENT_SPECIFIED", + "RESOLVED_FROM_ADDRESS", + "SOURCE_UNSPECIFIED" + ], + "enumDescriptions": [ + "Building.coordinates are set to the coordinates included in the request.", + "Building.coordinates are automatically populated based on the postal address.", + "Defaults to RESOLVED_FROM_ADDRESS if postal address is provided. Otherwise, defaults to CLIENT_SPECIFIED if coordinates are provided." + ], + "location": "query", + "type": "string" + }, + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/buildings/{buildingId}", + "request": { + "$ref": "Building" + }, + "response": { + "$ref": "Building" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar" + ] + } + } + }, + "calendars": { + "methods": { + "delete": { + "description": "Deletes a calendar resource.", + "httpMethod": "DELETE", + "id": "directory.resources.calendars.delete", + "parameterOrder": [ + "customer", + "calendarResourceId" + ], + "parameters": { + "calendarResourceId": { + "description": "The unique ID of the calendar resource to delete.", + "location": "path", + "required": true, + "type": "string" + }, + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/calendars/{calendarResourceId}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar" + ] + }, + "get": { + "description": "Retrieves a calendar resource.", + "httpMethod": "GET", + "id": "directory.resources.calendars.get", + "parameterOrder": [ + "customer", + "calendarResourceId" + ], + "parameters": { + "calendarResourceId": { + "description": "The unique ID of the calendar resource to retrieve.", + "location": "path", + "required": true, + "type": "string" + }, + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/calendars/{calendarResourceId}", + "response": { + "$ref": "CalendarResource" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar", + "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" + ] + }, + "insert": { + "description": "Inserts a calendar resource.", + "httpMethod": "POST", + "id": "directory.resources.calendars.insert", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/calendars", + "request": { + "$ref": "CalendarResource" + }, + "response": { + "$ref": "CalendarResource" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar" + ] + }, + "list": { + "description": "Retrieves a list of calendar resources for an account.", + "httpMethod": "GET", + "id": "directory.resources.calendars.list", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + }, + "maxResults": { + "description": "Maximum number of results to return.", + "format": "int32", + "location": "query", + "maximum": "500", + "minimum": "1", + "type": "integer" + }, + "orderBy": { + "description": "Field(s) to sort results by in either ascending or descending order. Supported fields include resourceId, resourceName, capacity, buildingId, and floorName. If no order is specified, defaults to ascending. Should be of the form \"field [asc|desc], field [asc|desc], ...\". For example buildingId, capacity desc would return results sorted first by buildingId in ascending order then by capacity in descending order.", + "location": "query", + "type": "string" + }, + "pageToken": { + "description": "Token to specify the next page in the list.", + "location": "query", + "type": "string" + }, + "query": { + "description": "String query used to filter results. Should be of the form \"field operator value\" where field can be any of supported fields and operators can be any of supported operations. Operators include '=' for exact match and ':' for prefix match or HAS match where applicable. For prefix match, the value should always be followed by a *. Supported fields include generatedResourceName, name, buildingId, featureInstances.feature.name. For example buildingId=US-NYC-9TH AND featureInstances.feature.name:Phone.", + "location": "query", + "type": "string" + } + }, + "path": "customer/{customer}/resources/calendars", + "response": { + "$ref": "CalendarResources" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar", + "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" + ] + }, + "patch": { + "description": "Updates a calendar resource.\n\nThis method supports patch semantics, meaning you only need to include the fields you wish to update. Fields that are not present in the request will be preserved. This method supports patch semantics.", + "httpMethod": "PATCH", + "id": "directory.resources.calendars.patch", + "parameterOrder": [ + "customer", + "calendarResourceId" + ], + "parameters": { + "calendarResourceId": { + "description": "The unique ID of the calendar resource to update.", + "location": "path", + "required": true, + "type": "string" + }, + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/calendars/{calendarResourceId}", + "request": { + "$ref": "CalendarResource" + }, + "response": { + "$ref": "CalendarResource" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar" + ] + }, + "update": { + "description": "Updates a calendar resource.\n\nThis method supports patch semantics, meaning you only need to include the fields you wish to update. Fields that are not present in the request will be preserved.", + "httpMethod": "PUT", + "id": "directory.resources.calendars.update", + "parameterOrder": [ + "customer", + "calendarResourceId" + ], + "parameters": { + "calendarResourceId": { + "description": "The unique ID of the calendar resource to update.", + "location": "path", + "required": true, + "type": "string" + }, + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/calendars/{calendarResourceId}", + "request": { + "$ref": "CalendarResource" + }, + "response": { + "$ref": "CalendarResource" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar" + ] + } + } + }, + "features": { + "methods": { + "delete": { + "description": "Deletes a feature.", + "httpMethod": "DELETE", + "id": "directory.resources.features.delete", + "parameterOrder": [ + "customer", + "featureKey" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + }, + "featureKey": { + "description": "The unique ID of the feature to delete.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/features/{featureKey}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar" + ] + }, + "get": { + "description": "Retrieves a feature.", + "httpMethod": "GET", + "id": "directory.resources.features.get", + "parameterOrder": [ + "customer", + "featureKey" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + }, + "featureKey": { + "description": "The unique ID of the feature to retrieve.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/features/{featureKey}", + "response": { + "$ref": "Feature" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar", + "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" + ] + }, + "insert": { + "description": "Inserts a feature.", + "httpMethod": "POST", + "id": "directory.resources.features.insert", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/features", + "request": { + "$ref": "Feature" + }, + "response": { + "$ref": "Feature" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar" + ] + }, + "list": { + "description": "Retrieves a list of features for an account.", + "httpMethod": "GET", + "id": "directory.resources.features.list", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + }, + "maxResults": { + "description": "Maximum number of results to return.", + "format": "int32", + "location": "query", + "maximum": "500", + "minimum": "1", + "type": "integer" + }, + "pageToken": { + "description": "Token to specify the next page in the list.", + "location": "query", + "type": "string" + } + }, + "path": "customer/{customer}/resources/features", + "response": { + "$ref": "Features" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar", + "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" + ] + }, + "patch": { + "description": "Updates a feature. This method supports patch semantics.", + "httpMethod": "PATCH", + "id": "directory.resources.features.patch", + "parameterOrder": [ + "customer", + "featureKey" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + }, + "featureKey": { + "description": "The unique ID of the feature to update.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/features/{featureKey}", + "request": { + "$ref": "Feature" + }, + "response": { + "$ref": "Feature" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar" + ] + }, + "rename": { + "description": "Renames a feature.", + "httpMethod": "POST", + "id": "directory.resources.features.rename", + "parameterOrder": [ + "customer", + "oldName" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + }, + "oldName": { + "description": "The unique ID of the feature to rename.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/features/{oldName}/rename", + "request": { + "$ref": "FeatureRename" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar" + ] + }, + "update": { + "description": "Updates a feature.", + "httpMethod": "PUT", + "id": "directory.resources.features.update", + "parameterOrder": [ + "customer", + "featureKey" + ], + "parameters": { + "customer": { + "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + "location": "path", + "required": true, + "type": "string" + }, + "featureKey": { + "description": "The unique ID of the feature to update.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/resources/features/{featureKey}", + "request": { + "$ref": "Feature" + }, + "response": { + "$ref": "Feature" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.resource.calendar" + ] + } + } + } + } + }, + "roleAssignments": { + "methods": { + "delete": { + "description": "Deletes a role assignment.", + "httpMethod": "DELETE", + "id": "directory.roleAssignments.delete", + "parameterOrder": [ + "customer", + "roleAssignmentId" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "roleAssignmentId": { + "description": "Immutable ID of the role assignment.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/roleassignments/{roleAssignmentId}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.rolemanagement" + ] + }, + "get": { + "description": "Retrieve a role assignment.", + "httpMethod": "GET", + "id": "directory.roleAssignments.get", + "parameterOrder": [ + "customer", + "roleAssignmentId" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "roleAssignmentId": { + "description": "Immutable ID of the role assignment.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/roleassignments/{roleAssignmentId}", + "response": { + "$ref": "RoleAssignment" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.rolemanagement", + "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" + ] + }, + "insert": { + "description": "Creates a role assignment.", + "httpMethod": "POST", + "id": "directory.roleAssignments.insert", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/roleassignments", + "request": { + "$ref": "RoleAssignment" + }, + "response": { + "$ref": "RoleAssignment" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.rolemanagement" + ] + }, + "list": { + "description": "Retrieves a paginated list of all roleAssignments.", + "httpMethod": "GET", + "id": "directory.roleAssignments.list", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "maxResults": { + "description": "Maximum number of results to return.", + "format": "int32", + "location": "query", + "maximum": "200", + "minimum": "1", + "type": "integer" + }, + "pageToken": { + "description": "Token to specify the next page in the list.", + "location": "query", + "type": "string" + }, + "roleId": { + "description": "Immutable ID of a role. If included in the request, returns only role assignments containing this role ID.", + "location": "query", + "type": "string" + }, + "userKey": { + "description": "The user's primary email address, alias email address, or unique user ID. If included in the request, returns role assignments only for this user.", + "location": "query", + "type": "string" + } + }, + "path": "customer/{customer}/roleassignments", + "response": { + "$ref": "RoleAssignments" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.rolemanagement", + "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" + ] + } + } + }, + "roles": { + "methods": { + "delete": { + "description": "Deletes a role.", + "httpMethod": "DELETE", + "id": "directory.roles.delete", + "parameterOrder": [ + "customer", + "roleId" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "roleId": { + "description": "Immutable ID of the role.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/roles/{roleId}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.rolemanagement" + ] + }, + "get": { + "description": "Retrieves a role.", + "httpMethod": "GET", + "id": "directory.roles.get", + "parameterOrder": [ + "customer", + "roleId" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "roleId": { + "description": "Immutable ID of the role.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/roles/{roleId}", + "response": { + "$ref": "Role" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.rolemanagement", + "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" + ] + }, + "insert": { + "description": "Creates a role.", + "httpMethod": "POST", + "id": "directory.roles.insert", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/roles", + "request": { + "$ref": "Role" + }, + "response": { + "$ref": "Role" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.rolemanagement" + ] + }, + "list": { + "description": "Retrieves a paginated list of all the roles in a domain.", + "httpMethod": "GET", + "id": "directory.roles.list", + "parameterOrder": [ + "customer" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "maxResults": { + "description": "Maximum number of results to return.", + "format": "int32", + "location": "query", + "maximum": "100", + "minimum": "1", + "type": "integer" + }, + "pageToken": { + "description": "Token to specify the next page in the list.", + "location": "query", + "type": "string" + } + }, + "path": "customer/{customer}/roles", + "response": { + "$ref": "Roles" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.rolemanagement", + "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" + ] + }, + "patch": { + "description": "Updates a role. This method supports patch semantics.", + "httpMethod": "PATCH", + "id": "directory.roles.patch", + "parameterOrder": [ + "customer", + "roleId" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "roleId": { + "description": "Immutable ID of the role.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/roles/{roleId}", + "request": { + "$ref": "Role" + }, + "response": { + "$ref": "Role" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.rolemanagement" + ] + }, + "update": { + "description": "Updates a role.", + "httpMethod": "PUT", + "id": "directory.roles.update", + "parameterOrder": [ + "customer", + "roleId" + ], + "parameters": { + "customer": { + "description": "Immutable ID of the G Suite account.", + "location": "path", + "required": true, + "type": "string" + }, + "roleId": { + "description": "Immutable ID of the role.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customer}/roles/{roleId}", + "request": { + "$ref": "Role" + }, + "response": { + "$ref": "Role" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.rolemanagement" + ] + } + } + }, + "schemas": { + "methods": { + "delete": { + "description": "Delete schema", + "httpMethod": "DELETE", + "id": "directory.schemas.delete", + "parameterOrder": [ + "customerId", + "schemaKey" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "schemaKey": { + "description": "Name or immutable ID of the schema", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/schemas/{schemaKey}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.userschema" + ] + }, + "get": { + "description": "Retrieve schema", + "httpMethod": "GET", + "id": "directory.schemas.get", + "parameterOrder": [ + "customerId", + "schemaKey" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "schemaKey": { + "description": "Name or immutable ID of the schema", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/schemas/{schemaKey}", + "response": { + "$ref": "Schema" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.userschema", + "https://www.googleapis.com/auth/admin.directory.userschema.readonly" + ] + }, + "insert": { + "description": "Create schema.", + "httpMethod": "POST", + "id": "directory.schemas.insert", + "parameterOrder": [ + "customerId" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/schemas", + "request": { + "$ref": "Schema" + }, + "response": { + "$ref": "Schema" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.userschema" + ] + }, + "list": { + "description": "Retrieve all schemas for a customer", + "httpMethod": "GET", + "id": "directory.schemas.list", + "parameterOrder": [ + "customerId" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/schemas", + "response": { + "$ref": "Schemas" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.userschema", + "https://www.googleapis.com/auth/admin.directory.userschema.readonly" + ] + }, + "patch": { + "description": "Update schema. This method supports patch semantics.", + "httpMethod": "PATCH", + "id": "directory.schemas.patch", + "parameterOrder": [ + "customerId", + "schemaKey" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "schemaKey": { + "description": "Name or immutable ID of the schema.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/schemas/{schemaKey}", + "request": { + "$ref": "Schema" + }, + "response": { + "$ref": "Schema" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.userschema" + ] + }, + "update": { + "description": "Update schema", + "httpMethod": "PUT", + "id": "directory.schemas.update", + "parameterOrder": [ + "customerId", + "schemaKey" + ], + "parameters": { + "customerId": { + "description": "Immutable ID of the G Suite account", + "location": "path", + "required": true, + "type": "string" + }, + "schemaKey": { + "description": "Name or immutable ID of the schema.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "customer/{customerId}/schemas/{schemaKey}", + "request": { + "$ref": "Schema" + }, + "response": { + "$ref": "Schema" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.userschema" + ] + } + } + }, + "tokens": { + "methods": { + "delete": { + "description": "Delete all access tokens issued by a user for an application.", + "httpMethod": "DELETE", + "id": "directory.tokens.delete", + "parameterOrder": [ + "userKey", + "clientId" + ], + "parameters": { + "clientId": { + "description": "The Client ID of the application the token is issued to.", + "location": "path", + "required": true, + "type": "string" + }, + "userKey": { + "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/tokens/{clientId}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user.security" + ] + }, + "get": { + "description": "Get information about an access token issued by a user.", + "httpMethod": "GET", + "id": "directory.tokens.get", + "parameterOrder": [ + "userKey", + "clientId" + ], + "parameters": { + "clientId": { + "description": "The Client ID of the application the token is issued to.", + "location": "path", + "required": true, + "type": "string" + }, + "userKey": { + "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/tokens/{clientId}", + "response": { + "$ref": "Token" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user.security" + ] + }, + "list": { + "description": "Returns the set of tokens specified user has issued to 3rd party applications.", + "httpMethod": "GET", + "id": "directory.tokens.list", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/tokens", + "response": { + "$ref": "Tokens" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user.security" + ] + } + } + }, + "users": { + "methods": { + "delete": { + "description": "Delete user", + "httpMethod": "DELETE", + "id": "directory.users.delete", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Email or immutable ID of the user", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user" + ] + }, + "get": { + "description": "retrieve user", + "httpMethod": "GET", + "id": "directory.users.get", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "customFieldMask": { + "description": "Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.", + "location": "query", + "type": "string" + }, + "projection": { + "default": "basic", + "description": "What subset of fields to fetch for this user.", + "enum": [ + "basic", + "custom", + "full" + ], + "enumDescriptions": [ + "Do not include any custom fields for the user.", + "Include custom fields from schemas mentioned in customFieldMask.", + "Include all fields associated with this user." + ], + "location": "query", + "type": "string" + }, + "userKey": { + "description": "Email or immutable ID of the user", + "location": "path", + "required": true, + "type": "string" + }, + "viewType": { + "default": "admin_view", + "description": "Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.", + "enum": [ + "admin_view", + "domain_public" + ], + "enumDescriptions": [ + "Fetches the ADMIN_VIEW of the user.", + "Fetches the DOMAIN_PUBLIC view of the user." + ], + "location": "query", + "type": "string" + } + }, + "path": "users/{userKey}", + "response": { + "$ref": "User" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user", + "https://www.googleapis.com/auth/admin.directory.user.readonly" + ] + }, + "insert": { + "description": "create user.", + "httpMethod": "POST", + "id": "directory.users.insert", + "path": "users", + "request": { + "$ref": "User" + }, + "response": { + "$ref": "User" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user" + ] + }, + "list": { + "description": "Retrieve either deleted users or all users in a domain (paginated)", + "httpMethod": "GET", + "id": "directory.users.list", + "parameters": { + "customFieldMask": { + "description": "Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.", + "location": "query", + "type": "string" + }, + "customer": { + "description": "Immutable ID of the G Suite account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain.", + "location": "query", + "type": "string" + }, + "domain": { + "description": "Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead.", + "location": "query", + "type": "string" + }, + "event": { + "description": "Event on which subscription is intended (if subscribing)", + "enum": [ + "add", + "delete", + "makeAdmin", + "undelete", + "update" + ], + "enumDescriptions": [ + "User Created Event", + "User Deleted Event", + "User Admin Status Change Event", + "User Undeleted Event", + "User Updated Event" + ], + "location": "query", + "type": "string" + }, + "maxResults": { + "default": "100", + "description": "Maximum number of results to return.", + "format": "int32", + "location": "query", + "maximum": "500", + "minimum": "1", + "type": "integer" + }, + "orderBy": { + "description": "Column to use for sorting results", + "enum": [ + "email", + "familyName", + "givenName" + ], + "enumDescriptions": [ + "Primary email of the user.", + "User's family name.", + "User's given name." + ], + "location": "query", + "type": "string" + }, + "pageToken": { + "description": "Token to specify next page in the list", + "location": "query", + "type": "string" + }, + "projection": { + "default": "basic", + "description": "What subset of fields to fetch for this user.", + "enum": [ + "basic", + "custom", + "full" + ], + "enumDescriptions": [ + "Do not include any custom fields for the user.", + "Include custom fields from schemas mentioned in customFieldMask.", + "Include all fields associated with this user." + ], + "location": "query", + "type": "string" + }, + "query": { + "description": "Query string search. Should be of the form \"\". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users", + "location": "query", + "type": "string" + }, + "showDeleted": { + "description": "If set to true, retrieves the list of deleted users. (Default: false)", + "location": "query", + "type": "string" + }, + "sortOrder": { + "description": "Whether to return results in ascending or descending order.", + "enum": [ + "ASCENDING", + "DESCENDING" + ], + "enumDescriptions": [ + "Ascending order.", + "Descending order." + ], + "location": "query", + "type": "string" + }, + "viewType": { + "default": "admin_view", + "description": "Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.", + "enum": [ + "admin_view", + "domain_public" + ], + "enumDescriptions": [ + "Fetches the ADMIN_VIEW of the user.", + "Fetches the DOMAIN_PUBLIC view of the user." + ], + "location": "query", + "type": "string" + } + }, + "path": "users", + "response": { + "$ref": "Users" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user", + "https://www.googleapis.com/auth/admin.directory.user.readonly" + ], + "supportsSubscription": true + }, + "makeAdmin": { + "description": "change admin status of a user", + "httpMethod": "POST", + "id": "directory.users.makeAdmin", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Email or immutable ID of the user as admin", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/makeAdmin", + "request": { + "$ref": "UserMakeAdmin" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user" + ] + }, + "patch": { + "description": "update user. This method supports patch semantics.", + "httpMethod": "PATCH", + "id": "directory.users.patch", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Email or immutable ID of the user. If ID, it should match with id of user object", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}", + "request": { + "$ref": "User" + }, + "response": { + "$ref": "User" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user" + ] + }, + "undelete": { + "description": "Undelete a deleted user", + "httpMethod": "POST", + "id": "directory.users.undelete", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "The immutable id of the user", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/undelete", + "request": { + "$ref": "UserUndelete" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user" + ] + }, + "update": { + "description": "update user", + "httpMethod": "PUT", + "id": "directory.users.update", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Email or immutable ID of the user. If ID, it should match with id of user object", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}", + "request": { + "$ref": "User" + }, + "response": { + "$ref": "User" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user" + ] + }, + "watch": { + "description": "Watch for changes in users list", + "httpMethod": "POST", + "id": "directory.users.watch", + "parameters": { + "customFieldMask": { + "description": "Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.", + "location": "query", + "type": "string" + }, + "customer": { + "description": "Immutable ID of the G Suite account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain.", + "location": "query", + "type": "string" + }, + "domain": { + "description": "Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead.", + "location": "query", + "type": "string" + }, + "event": { + "description": "Event on which subscription is intended (if subscribing)", + "enum": [ + "add", + "delete", + "makeAdmin", + "undelete", + "update" + ], + "enumDescriptions": [ + "User Created Event", + "User Deleted Event", + "User Admin Status Change Event", + "User Undeleted Event", + "User Updated Event" + ], + "location": "query", + "type": "string" + }, + "maxResults": { + "default": "100", + "description": "Maximum number of results to return.", + "format": "int32", + "location": "query", + "maximum": "500", + "minimum": "1", + "type": "integer" + }, + "orderBy": { + "description": "Column to use for sorting results", + "enum": [ + "email", + "familyName", + "givenName" + ], + "enumDescriptions": [ + "Primary email of the user.", + "User's family name.", + "User's given name." + ], + "location": "query", + "type": "string" + }, + "pageToken": { + "description": "Token to specify next page in the list", + "location": "query", + "type": "string" + }, + "projection": { + "default": "basic", + "description": "What subset of fields to fetch for this user.", + "enum": [ + "basic", + "custom", + "full" + ], + "enumDescriptions": [ + "Do not include any custom fields for the user.", + "Include custom fields from schemas mentioned in customFieldMask.", + "Include all fields associated with this user." + ], + "location": "query", + "type": "string" + }, + "query": { + "description": "Query string search. Should be of the form \"\". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users", + "location": "query", + "type": "string" + }, + "showDeleted": { + "description": "If set to true, retrieves the list of deleted users. (Default: false)", + "location": "query", + "type": "string" + }, + "sortOrder": { + "description": "Whether to return results in ascending or descending order.", + "enum": [ + "ASCENDING", + "DESCENDING" + ], + "enumDescriptions": [ + "Ascending order.", + "Descending order." + ], + "location": "query", + "type": "string" + }, + "viewType": { + "default": "admin_view", + "description": "Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.", + "enum": [ + "admin_view", + "domain_public" + ], + "enumDescriptions": [ + "Fetches the ADMIN_VIEW of the user.", + "Fetches the DOMAIN_PUBLIC view of the user." + ], + "location": "query", + "type": "string" + } + }, + "path": "users/watch", + "request": { + "$ref": "Channel", + "parameterName": "resource" + }, + "response": { + "$ref": "Channel" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user", + "https://www.googleapis.com/auth/admin.directory.user.readonly" + ], + "supportsSubscription": true + } + }, + "resources": { + "aliases": { + "methods": { + "delete": { + "description": "Remove a alias for the user", + "httpMethod": "DELETE", + "id": "directory.users.aliases.delete", + "parameterOrder": [ + "userKey", + "alias" + ], + "parameters": { + "alias": { + "description": "The alias to be removed", + "location": "path", + "required": true, + "type": "string" + }, + "userKey": { + "description": "Email or immutable ID of the user", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/aliases/{alias}", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user", + "https://www.googleapis.com/auth/admin.directory.user.alias" + ] + }, + "insert": { + "description": "Add a alias for the user", + "httpMethod": "POST", + "id": "directory.users.aliases.insert", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Email or immutable ID of the user", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/aliases", + "request": { + "$ref": "Alias" + }, + "response": { + "$ref": "Alias" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user", + "https://www.googleapis.com/auth/admin.directory.user.alias" + ] + }, + "list": { + "description": "List all aliases for a user", + "httpMethod": "GET", + "id": "directory.users.aliases.list", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "event": { + "description": "Event on which subscription is intended (if subscribing)", + "enum": [ + "add", + "delete" + ], + "enumDescriptions": [ + "Alias Created Event", + "Alias Deleted Event" + ], + "location": "query", + "type": "string" + }, + "userKey": { + "description": "Email or immutable ID of the user", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/aliases", + "response": { + "$ref": "Aliases" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user", + "https://www.googleapis.com/auth/admin.directory.user.alias", + "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", + "https://www.googleapis.com/auth/admin.directory.user.readonly" + ], + "supportsSubscription": true + }, + "watch": { + "description": "Watch for changes in user aliases list", + "httpMethod": "POST", + "id": "directory.users.aliases.watch", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "event": { + "description": "Event on which subscription is intended (if subscribing)", + "enum": [ + "add", + "delete" + ], + "enumDescriptions": [ + "Alias Created Event", + "Alias Deleted Event" + ], + "location": "query", + "type": "string" + }, + "userKey": { + "description": "Email or immutable ID of the user", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/aliases/watch", + "request": { + "$ref": "Channel", + "parameterName": "resource" + }, + "response": { + "$ref": "Channel" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user", + "https://www.googleapis.com/auth/admin.directory.user.alias", + "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", + "https://www.googleapis.com/auth/admin.directory.user.readonly" + ], + "supportsSubscription": true + } + } + }, + "photos": { + "methods": { + "delete": { + "description": "Remove photos for the user", + "httpMethod": "DELETE", + "id": "directory.users.photos.delete", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Email or immutable ID of the user", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/photos/thumbnail", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user" + ] + }, + "get": { + "description": "Retrieve photo of a user", + "httpMethod": "GET", + "id": "directory.users.photos.get", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Email or immutable ID of the user", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/photos/thumbnail", + "response": { + "$ref": "UserPhoto" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user", + "https://www.googleapis.com/auth/admin.directory.user.readonly" + ] + }, + "patch": { + "description": "Add a photo for the user. This method supports patch semantics.", + "httpMethod": "PATCH", + "id": "directory.users.photos.patch", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Email or immutable ID of the user", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/photos/thumbnail", + "request": { + "$ref": "UserPhoto" + }, + "response": { + "$ref": "UserPhoto" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user" + ] + }, + "update": { + "description": "Add a photo for the user", + "httpMethod": "PUT", + "id": "directory.users.photos.update", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Email or immutable ID of the user", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/photos/thumbnail", + "request": { + "$ref": "UserPhoto" + }, + "response": { + "$ref": "UserPhoto" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user" + ] + } + } + } + } + }, + "verificationCodes": { + "methods": { + "generate": { + "description": "Generate new backup verification codes for the user.", + "httpMethod": "POST", + "id": "directory.verificationCodes.generate", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Email or immutable ID of the user", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/verificationCodes/generate", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user.security" + ] + }, + "invalidate": { + "description": "Invalidate the current backup verification codes for the user.", + "httpMethod": "POST", + "id": "directory.verificationCodes.invalidate", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Email or immutable ID of the user", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/verificationCodes/invalidate", + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user.security" + ] + }, + "list": { + "description": "Returns the current set of valid backup verification codes for the specified user.", + "httpMethod": "GET", + "id": "directory.verificationCodes.list", + "parameterOrder": [ + "userKey" + ], + "parameters": { + "userKey": { + "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "users/{userKey}/verificationCodes", + "response": { + "$ref": "VerificationCodes" + }, + "scopes": [ + "https://www.googleapis.com/auth/admin.directory.user.security" + ] + } + } + } + }, + "revision": "20190806", + "rootUrl": "https://www.googleapis.com/", + "schemas": { + "Alias": { + "description": "JSON template for Alias object in Directory API.", + "id": "Alias", + "properties": { + "alias": { + "description": "A alias email", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "id": { + "description": "Unique id of the group (Read-only) Unique id of the user (Read-only)", + "type": "string" + }, + "kind": { + "default": "admin#directory#alias", + "description": "Kind of resource this is.", + "type": "string" + }, + "primaryEmail": { + "description": "Group's primary email (Read-only) User's primary email (Read-only)", + "type": "string" + } + }, + "type": "object" + }, + "Aliases": { + "description": "JSON response template to list aliases in Directory API.", + "id": "Aliases", + "properties": { + "aliases": { + "description": "List of alias objects.", + "items": { + "type": "any" + }, + "type": "array" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#aliases", + "description": "Kind of resource this is.", + "type": "string" + } + }, + "type": "object" + }, + "AppAccessCollections": { + "description": "JSON template for App Access Collections Resource object in Directory API.", + "id": "AppAccessCollections", + "properties": { + "blockedApiAccessBuckets": { + "description": "List of blocked api access buckets.", + "items": { + "type": "string" + }, + "type": "array" + }, + "enforceSettingsForAndroidDrive": { + "description": "Boolean to indicate whether to enforce app access settings on Android Drive or not.", + "type": "boolean" + }, + "errorMessage": { + "description": "Error message provided by the Admin that will be shown to the user when an app is blocked.", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#appaccesscollection", + "description": "Identifies the resource as an app access collection. Value: admin#directory#appaccesscollection", + "type": "string" + }, + "resourceId": { + "description": "Unique ID of app access collection. (Readonly)", + "format": "int64", + "type": "string" + }, + "resourceName": { + "description": "Resource name given by the customer while creating/updating. Should be unique under given customer.", + "type": "string" + }, + "trustDomainOwnedApps": { + "description": "Boolean that indicates whether to trust domain owned apps.", + "type": "boolean" + } + }, + "type": "object" + }, + "Asp": { + "description": "The template that returns individual ASP (Access Code) data.", + "id": "Asp", + "properties": { + "codeId": { + "description": "The unique ID of the ASP.", + "format": "int32", + "type": "integer" + }, + "creationTime": { + "description": "The time when the ASP was created. Expressed in Unix time format.", + "format": "int64", + "type": "string" + }, + "etag": { + "description": "ETag of the ASP.", + "type": "string" + }, + "kind": { + "default": "admin#directory#asp", + "description": "The type of the API resource. This is always admin#directory#asp.", + "type": "string" + }, + "lastTimeUsed": { + "description": "The time when the ASP was last used. Expressed in Unix time format.", + "format": "int64", + "type": "string" + }, + "name": { + "description": "The name of the application that the user, represented by their userId, entered when the ASP was created.", + "type": "string" + }, + "userKey": { + "description": "The unique ID of the user who issued the ASP.", + "type": "string" + } + }, + "type": "object" + }, + "Asps": { + "id": "Asps", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "items": { + "description": "A list of ASP resources.", + "items": { + "$ref": "Asp" + }, + "type": "array" + }, + "kind": { + "default": "admin#directory#aspList", + "description": "The type of the API resource. This is always admin#directory#aspList.", + "type": "string" + } + }, + "type": "object" + }, + "Building": { + "description": "JSON template for Building object in Directory API.", + "id": "Building", + "properties": { + "address": { + "$ref": "BuildingAddress", + "description": "The postal address of the building. See PostalAddress for details. Note that only a single address line and region code are required." + }, + "buildingId": { + "description": "Unique identifier for the building. The maximum length is 100 characters.", + "type": "string" + }, + "buildingName": { + "description": "The building name as seen by users in Calendar. Must be unique for the customer. For example, \"NYC-CHEL\". The maximum length is 100 characters.", + "type": "string" + }, + "coordinates": { + "$ref": "BuildingCoordinates", + "description": "The geographic coordinates of the center of the building, expressed as latitude and longitude in decimal degrees." + }, + "description": { + "description": "A brief description of the building. For example, \"Chelsea Market\".", + "type": "string" + }, + "etags": { + "description": "ETag of the resource.", + "type": "string" + }, + "floorNames": { + "description": "The display names for all floors in this building. The floors are expected to be sorted in ascending order, from lowest floor to highest floor. For example, [\"B2\", \"B1\", \"L\", \"1\", \"2\", \"2M\", \"3\", \"PH\"] Must contain at least one entry.", + "items": { + "type": "string" + }, + "type": "array" + }, + "kind": { + "default": "admin#directory#resources#buildings#Building", + "description": "Kind of resource this is.", + "type": "string" + } + }, + "type": "object" + }, + "BuildingAddress": { + "description": "JSON template for the postal address of a building in Directory API.", + "id": "BuildingAddress", + "properties": { + "addressLines": { + "description": "Unstructured address lines describing the lower levels of an address.", + "items": { + "type": "string" + }, + "type": "array" + }, + "administrativeArea": { + "description": "Optional. Highest administrative subdivision which is used for postal addresses of a country or region.", + "type": "string" + }, + "languageCode": { + "description": "Optional. BCP-47 language code of the contents of this address (if known).", + "type": "string" + }, + "locality": { + "description": "Optional. Generally refers to the city/town portion of the address. Examples: US city, IT comune, UK post town. In regions of the world where localities are not well defined or do not fit into this structure well, leave locality empty and use addressLines.", + "type": "string" + }, + "postalCode": { + "description": "Optional. Postal code of the address.", + "type": "string" + }, + "regionCode": { + "description": "Required. CLDR region code of the country/region of the address.", + "type": "string" + }, + "sublocality": { + "description": "Optional. Sublocality of the address.", + "type": "string" + } + }, + "type": "object" + }, + "BuildingCoordinates": { + "description": "JSON template for coordinates of a building in Directory API.", + "id": "BuildingCoordinates", + "properties": { + "latitude": { + "description": "Latitude in decimal degrees.", + "format": "double", + "type": "number" + }, + "longitude": { + "description": "Longitude in decimal degrees.", + "format": "double", + "type": "number" + } + }, + "type": "object" + }, + "Buildings": { + "description": "JSON template for Building List Response object in Directory API.", + "id": "Buildings", + "properties": { + "buildings": { + "description": "The Buildings in this page of results.", + "items": { + "$ref": "Building" + }, + "type": "array" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#resources#buildings#buildingsList", + "description": "Kind of resource this is.", + "type": "string" + }, + "nextPageToken": { + "description": "The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results.", + "type": "string" + } + }, + "type": "object" + }, + "CalendarResource": { + "description": "JSON template for Calendar Resource object in Directory API.", + "id": "CalendarResource", + "properties": { + "buildingId": { + "description": "Unique ID for the building a resource is located in.", + "type": "string" + }, + "capacity": { + "description": "Capacity of a resource, number of seats in a room.", + "format": "int32", + "type": "integer" + }, + "etags": { + "description": "ETag of the resource.", + "type": "string" + }, + "featureInstances": { + "type": "any" + }, + "floorName": { + "description": "Name of the floor a resource is located on.", + "type": "string" + }, + "floorSection": { + "description": "Name of the section within a floor a resource is located in.", + "type": "string" + }, + "generatedResourceName": { + "description": "The read-only auto-generated name of the calendar resource which includes metadata about the resource such as building name, floor, capacity, etc. For example, \"NYC-2-Training Room 1A (16)\".", + "type": "string" + }, + "kind": { + "default": "admin#directory#resources#calendars#CalendarResource", + "description": "The type of the resource. For calendar resources, the value is admin#directory#resources#calendars#CalendarResource.", + "type": "string" + }, + "resourceCategory": { + "description": "The category of the calendar resource. Either CONFERENCE_ROOM or OTHER. Legacy data is set to CATEGORY_UNKNOWN.", + "type": "string" + }, + "resourceDescription": { + "description": "Description of the resource, visible only to admins.", + "type": "string" + }, + "resourceEmail": { + "description": "The read-only email for the calendar resource. Generated as part of creating a new calendar resource.", + "type": "string" + }, + "resourceId": { + "annotations": { + "required": [ + "directory.resources.calendars.insert" + ] + }, + "description": "The unique ID for the calendar resource.", + "type": "string" + }, + "resourceName": { + "annotations": { + "required": [ + "directory.resources.calendars.insert" + ] + }, + "description": "The name of the calendar resource. For example, \"Training Room 1A\".", + "type": "string" + }, + "resourceType": { + "description": "The type of the calendar resource, intended for non-room resources.", + "type": "string" + }, + "userVisibleDescription": { + "description": "Description of the resource, visible to users and admins.", + "type": "string" + } + }, + "type": "object" + }, + "CalendarResources": { + "description": "JSON template for Calendar Resource List Response object in Directory API.", + "id": "CalendarResources", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "items": { + "description": "The CalendarResources in this page of results.", + "items": { + "$ref": "CalendarResource" + }, + "type": "array" + }, + "kind": { + "default": "admin#directory#resources#calendars#calendarResourcesList", + "description": "Identifies this as a collection of CalendarResources. This is always admin#directory#resources#calendars#calendarResourcesList.", + "type": "string" + }, + "nextPageToken": { + "description": "The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results.", + "type": "string" + } + }, + "type": "object" + }, + "Channel": { + "description": "An notification channel used to watch for resource changes.", + "id": "Channel", + "properties": { + "address": { + "description": "The address where notifications are delivered for this channel.", + "type": "string" + }, + "expiration": { + "description": "Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional.", + "format": "int64", + "type": "string" + }, + "id": { + "description": "A UUID or similar unique string that identifies this channel.", + "type": "string" + }, + "kind": { + "default": "api#channel", + "description": "Identifies this as a notification channel used to watch for changes to a resource, which is \"api#channel\".", + "type": "string" + }, + "params": { + "additionalProperties": { + "description": "Declares a new parameter by name.", + "type": "string" + }, + "description": "Additional parameters controlling delivery channel behavior. Optional.", + "type": "object" + }, + "payload": { + "description": "A Boolean value to indicate whether payload is wanted. Optional.", + "type": "boolean" + }, + "resourceId": { + "description": "An opaque ID that identifies the resource being watched on this channel. Stable across different API versions.", + "type": "string" + }, + "resourceUri": { + "description": "A version-specific identifier for the watched resource.", + "type": "string" + }, + "token": { + "description": "An arbitrary string delivered to the target address with each notification delivered over this channel. Optional.", + "type": "string" + }, + "type": { + "description": "The type of delivery mechanism used for this channel.", + "type": "string" + } + }, + "type": "object" + }, + "ChromeOsDevice": { + "description": "JSON template for Chrome Os Device resource in Directory API.", + "id": "ChromeOsDevice", + "properties": { + "activeTimeRanges": { + "description": "List of active time ranges (Read-only)", + "items": { + "properties": { + "activeTime": { + "description": "Duration in milliseconds", + "format": "int32", + "type": "integer" + }, + "date": { + "description": "Date of usage", + "format": "date", + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + }, + "annotatedAssetId": { + "description": "AssetId specified during enrollment or through later annotation", + "type": "string" + }, + "annotatedLocation": { + "description": "Address or location of the device as noted by the administrator", + "type": "string" + }, + "annotatedUser": { + "description": "User of the device", + "type": "string" + }, + "autoUpdateExpiration": { + "description": "(Read-only) The timestamp after which the device will stop receiving Chrome updates or support", + "format": "int64", + "type": "string" + }, + "bootMode": { + "description": "Chromebook boot mode (Read-only)", + "type": "string" + }, + "cpuStatusReports": { + "description": "Reports of CPU utilization and temperature (Read-only)", + "items": { + "properties": { + "cpuTemperatureInfo": { + "description": "List of CPU temperature samples.", + "items": { + "properties": { + "label": { + "description": "CPU label", + "type": "string" + }, + "temperature": { + "description": "Temperature in Celsius degrees.", + "format": "int32", + "type": "integer" + } + }, + "type": "object" + }, + "type": "array" + }, + "cpuUtilizationPercentageInfo": { + "items": { + "format": "int32", + "type": "integer" + }, + "type": "array" + }, + "reportTime": { + "description": "Date and time the report was received.", + "format": "date-time", + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + }, + "deviceFiles": { + "description": "List of device files to download (Read-only)", + "items": { + "properties": { + "createTime": { + "description": "Date and time the file was created", + "format": "date-time", + "type": "string" + }, + "downloadUrl": { + "description": "File download URL", + "type": "string" + }, + "name": { + "description": "File name", + "type": "string" + }, + "type": { + "description": "File type", + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + }, + "deviceId": { + "description": "Unique identifier of Chrome OS Device (Read-only)", + "type": "string" + }, + "diskVolumeReports": { + "description": "Reports of disk space and other info about mounted/connected volumes.", + "items": { + "properties": { + "volumeInfo": { + "description": "Disk volumes", + "items": { + "properties": { + "storageFree": { + "description": "Free disk space [in bytes]", + "format": "int64", + "type": "string" + }, + "storageTotal": { + "description": "Total disk space [in bytes]", + "format": "int64", + "type": "string" + }, + "volumeId": { + "description": "Volume id", + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + } + }, + "type": "object" + }, + "type": "array" + }, + "dockMacAddress": { + "description": "(Read-only) Built-in MAC address for the docking station that the device connected to. Factory sets Media access control address (MAC address) assigned for use by a dock. Currently this is only supported on the Dell Arcada / Sarien devices and the Dell WD19 / WD19TB Docking Station. It is reserved specifically for MAC pass through device policy. The format is twelve (12) hexadecimal digits without any delimiter (uppercase letters). This is only relevant for Dell devices.", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "ethernetMacAddress": { + "description": "Chromebook Mac Address on ethernet network interface (Read-only)", + "type": "string" + }, + "ethernetMacAddress0": { + "description": "(Read-only) MAC address used by the Chromebook’s internal ethernet port, and for onboard network (ethernet) interface. The format is twelve (12) hexadecimal digits without any delimiter (uppercase letters). This is only relevant for Dell devices.", + "type": "string" + }, + "firmwareVersion": { + "description": "Chromebook firmware version (Read-only)", + "type": "string" + }, + "kind": { + "default": "admin#directory#chromeosdevice", + "description": "Kind of resource this is.", + "type": "string" + }, + "lastEnrollmentTime": { + "description": "Date and time the device was last enrolled (Read-only)", + "format": "date-time", + "type": "string" + }, + "lastSync": { + "description": "Date and time the device was last synchronized with the policy settings in the G Suite administrator control panel (Read-only)", + "format": "date-time", + "type": "string" + }, + "macAddress": { + "description": "Chromebook Mac Address on wifi network interface (Read-only)", + "type": "string" + }, + "manufactureDate": { + "description": "(Read-only) The date the device was manufactured in yyyy-mm-dd format.", + "type": "string" + }, + "meid": { + "description": "Mobile Equipment identifier for the 3G mobile card in the Chromebook (Read-only)", + "type": "string" + }, + "model": { + "description": "Chromebook Model (Read-only)", + "type": "string" + }, + "notes": { + "description": "Notes added by the administrator", + "type": "string" + }, + "orderNumber": { + "description": "Chromebook order number (Read-only)", + "type": "string" + }, + "orgUnitPath": { + "description": "OrgUnit of the device", + "type": "string" + }, + "osVersion": { + "description": "Chromebook Os Version (Read-only)", + "type": "string" + }, + "platformVersion": { + "description": "Chromebook platform version (Read-only)", + "type": "string" + }, + "recentUsers": { + "description": "List of recent device users, in descending order by last login time (Read-only)", + "items": { + "properties": { + "email": { + "description": "Email address of the user. Present only if the user type is managed", + "type": "string" + }, + "type": { + "description": "The type of the user", + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + }, + "serialNumber": { + "description": "Chromebook serial number (Read-only)", + "type": "string" + }, + "status": { + "description": "status of the device (Read-only)", + "type": "string" + }, + "supportEndDate": { + "description": "Final date the device will be supported (Read-only)", + "format": "date-time", + "type": "string" + }, + "systemRamFreeReports": { + "description": "Reports of amounts of available RAM memory (Read-only)", + "items": { + "properties": { + "reportTime": { + "description": "Date and time the report was received.", + "format": "date-time", + "type": "string" + }, + "systemRamFreeInfo": { + "items": { + "format": "int64", + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "type": "array" + }, + "systemRamTotal": { + "description": "Total RAM on the device [in bytes] (Read-only)", + "format": "int64", + "type": "string" + }, + "tpmVersionInfo": { + "description": "Trusted Platform Module (TPM) (Read-only)", + "properties": { + "family": { + "description": "TPM family.", + "type": "string" + }, + "firmwareVersion": { + "description": "TPM firmware version.", + "type": "string" + }, + "manufacturer": { + "description": "TPM manufacturer code.", + "type": "string" + }, + "specLevel": { + "description": "TPM specification level.", + "type": "string" + }, + "tpmModel": { + "description": "TPM model number.", + "type": "string" + }, + "vendorSpecific": { + "description": "Vendor-specific information such as Vendor ID.", + "type": "string" + } + }, + "type": "object" + }, + "willAutoRenew": { + "description": "Will Chromebook auto renew after support end date (Read-only)", + "type": "boolean" + } + }, + "type": "object" + }, + "ChromeOsDeviceAction": { + "description": "JSON request template for firing actions on ChromeOs Device in Directory Devices API.", + "id": "ChromeOsDeviceAction", + "properties": { + "action": { + "annotations": { + "required": [ + "directory.chromeosdevices.action" + ] + }, + "description": "Action to be taken on the ChromeOs Device", + "type": "string" + }, + "deprovisionReason": { + "type": "string" + } + }, + "type": "object" + }, + "ChromeOsDevices": { + "description": "JSON response template for List Chrome OS Devices operation in Directory API.", + "id": "ChromeOsDevices", + "properties": { + "chromeosdevices": { + "description": "List of Chrome OS Device objects.", + "items": { + "$ref": "ChromeOsDevice" + }, + "type": "array" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#chromeosdevices", + "description": "Kind of resource this is.", + "type": "string" + }, + "nextPageToken": { + "description": "Token used to access next page of this result.", + "type": "string" + } + }, + "type": "object" + }, + "ChromeOsMoveDevicesToOu": { + "description": "JSON request template for moving ChromeOs Device to given OU in Directory Devices API.", + "id": "ChromeOsMoveDevicesToOu", + "properties": { + "deviceIds": { + "annotations": { + "required": [ + "directory.chromeosdevices.moveDevicesToOu" + ] + }, + "description": "ChromeOs Devices to be moved to OU", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "Customer": { + "description": "JSON template for Customer Resource object in Directory API.", + "id": "Customer", + "properties": { + "alternateEmail": { + "description": "The customer's secondary contact email address. This email address cannot be on the same domain as the customerDomain", + "type": "string" + }, + "customerCreationTime": { + "description": "The customer's creation time (Readonly)", + "format": "date-time", + "type": "string" + }, + "customerDomain": { + "description": "The customer's primary domain name string. Do not include the www prefix when creating a new customer.", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "id": { + "description": "The unique ID for the customer's G Suite account. (Readonly)", + "type": "string" + }, + "kind": { + "default": "admin#directory#customer", + "description": "Identifies the resource as a customer. Value: admin#directory#customer", + "type": "string" + }, + "language": { + "description": "The customer's ISO 639-2 language code. The default value is en-US", + "type": "string" + }, + "phoneNumber": { + "description": "The customer's contact phone number in E.164 format.", + "type": "string" + }, + "postalAddress": { + "$ref": "CustomerPostalAddress", + "description": "The customer's postal address information." + } + }, + "type": "object" + }, + "CustomerPostalAddress": { + "description": "JSON template for postal address of a customer.", + "id": "CustomerPostalAddress", + "properties": { + "addressLine1": { + "description": "A customer's physical address. The address can be composed of one to three lines.", + "type": "string" + }, + "addressLine2": { + "description": "Address line 2 of the address.", + "type": "string" + }, + "addressLine3": { + "description": "Address line 3 of the address.", + "type": "string" + }, + "contactName": { + "description": "The customer contact's name.", + "type": "string" + }, + "countryCode": { + "description": "This is a required property. For countryCode information see the ISO 3166 country code elements.", + "type": "string" + }, + "locality": { + "description": "Name of the locality. An example of a locality value is the city of San Francisco.", + "type": "string" + }, + "organizationName": { + "description": "The company or company division name.", + "type": "string" + }, + "postalCode": { + "description": "The postal code. A postalCode example is a postal zip code such as 10009. This is in accordance with - http://portablecontacts.net/draft-spec.html#address_element.", + "type": "string" + }, + "region": { + "description": "Name of the region. An example of a region value is NY for the state of New York.", + "type": "string" + } + }, + "type": "object" + }, + "DomainAlias": { + "description": "JSON template for Domain Alias object in Directory API.", + "id": "DomainAlias", + "properties": { + "creationTime": { + "description": "The creation time of the domain alias. (Read-only).", + "format": "int64", + "type": "string" + }, + "domainAliasName": { + "description": "The domain alias name.", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#domainAlias", + "description": "Kind of resource this is.", + "type": "string" + }, + "parentDomainName": { + "annotations": { + "required": [ + "directory.domains.insert" + ] + }, + "description": "The parent domain name that the domain alias is associated with. This can either be a primary or secondary domain name within a customer.", + "type": "string" + }, + "verified": { + "description": "Indicates the verification state of a domain alias. (Read-only)", + "type": "boolean" + } + }, + "type": "object" + }, + "DomainAliases": { + "description": "JSON response template to list domain aliases in Directory API.", + "id": "DomainAliases", + "properties": { + "domainAliases": { + "description": "List of domain alias objects.", + "items": { + "$ref": "DomainAlias" + }, + "type": "array" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#domainAliases", + "description": "Kind of resource this is.", + "type": "string" + } + }, + "type": "object" + }, + "Domains": { + "description": "JSON template for Domain object in Directory API.", + "id": "Domains", + "properties": { + "creationTime": { + "description": "Creation time of the domain. (Read-only).", + "format": "int64", + "type": "string" + }, + "domainAliases": { + "description": "List of domain alias objects. (Read-only)", + "items": { + "$ref": "DomainAlias" + }, + "type": "array" + }, + "domainName": { + "annotations": { + "required": [ + "directory.domains.insert" + ] + }, + "description": "The domain name of the customer.", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "isPrimary": { + "description": "Indicates if the domain is a primary domain (Read-only).", + "type": "boolean" + }, + "kind": { + "default": "admin#directory#domain", + "description": "Kind of resource this is.", + "type": "string" + }, + "verified": { + "description": "Indicates the verification state of a domain. (Read-only).", + "type": "boolean" + } + }, + "type": "object" + }, + "Domains2": { + "description": "JSON response template to list Domains in Directory API.", + "id": "Domains2", + "properties": { + "domains": { + "description": "List of domain objects.", + "items": { + "$ref": "Domains" + }, + "type": "array" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#domains", + "description": "Kind of resource this is.", + "type": "string" + } + }, + "type": "object" + }, + "Feature": { + "description": "JSON template for Feature object in Directory API.", + "id": "Feature", + "properties": { + "etags": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#resources#features#Feature", + "description": "Kind of resource this is.", + "type": "string" + }, + "name": { + "annotations": { + "required": [ + "directory.resources.features.insert" + ] + }, + "description": "The name of the feature.", + "type": "string" + } + }, + "type": "object" + }, + "FeatureInstance": { + "description": "JSON template for a \"feature instance\".", + "id": "FeatureInstance", + "properties": { + "feature": { + "$ref": "Feature", + "description": "The feature that this is an instance of. A calendar resource may have multiple instances of a feature." + } + }, + "type": "object" + }, + "FeatureRename": { + "description": "JSON request template for renaming a feature.", + "id": "FeatureRename", + "properties": { + "newName": { + "annotations": { + "required": [ + "directory.resources.features.rename" + ] + }, + "description": "New name of the feature.", + "type": "string" + } + }, + "type": "object" + }, + "Features": { + "description": "JSON template for Feature List Response object in Directory API.", + "id": "Features", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "features": { + "description": "The Features in this page of results.", + "items": { + "$ref": "Feature" + }, + "type": "array" + }, + "kind": { + "default": "admin#directory#resources#features#featuresList", + "description": "Kind of resource this is.", + "type": "string" + }, + "nextPageToken": { + "description": "The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results.", + "type": "string" + } + }, + "type": "object" + }, + "Group": { + "description": "JSON template for Group resource in Directory API.", + "id": "Group", + "properties": { + "adminCreated": { + "description": "Is the group created by admin (Read-only) *", + "type": "boolean" + }, + "aliases": { + "description": "List of aliases (Read-only)", + "items": { + "type": "string" + }, + "type": "array" + }, + "description": { + "description": "Description of the group", + "type": "string" + }, + "directMembersCount": { + "description": "Group direct members count", + "format": "int64", + "type": "string" + }, + "email": { + "annotations": { + "required": [ + "directory.groups.insert" + ] + }, + "description": "Email of Group", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "id": { + "description": "Unique identifier of Group (Read-only)", + "type": "string" + }, + "kind": { + "default": "admin#directory#group", + "description": "Kind of resource this is.", + "type": "string" + }, + "name": { + "description": "Group name", + "type": "string" + }, + "nonEditableAliases": { + "description": "List of non editable aliases (Read-only)", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "Groups": { + "description": "JSON response template for List Groups operation in Directory API.", + "id": "Groups", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "groups": { + "description": "List of group objects.", + "items": { + "$ref": "Group" + }, + "type": "array" + }, + "kind": { + "default": "admin#directory#groups", + "description": "Kind of resource this is.", + "type": "string" + }, + "nextPageToken": { + "description": "Token used to access next page of this result.", + "type": "string" + } + }, + "type": "object" + }, + "Member": { + "description": "JSON template for Member resource in Directory API.", + "id": "Member", + "properties": { + "delivery_settings": { + "description": "Delivery settings of member", + "type": "string" + }, + "email": { + "description": "Email of member (Read-only)", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "id": { + "description": "The unique ID of the group member. A member id can be used as a member request URI's memberKey. Unique identifier of group (Read-only) Unique identifier of member (Read-only)", + "type": "string" + }, + "kind": { + "default": "admin#directory#member", + "description": "Kind of resource this is.", + "type": "string" + }, + "role": { + "description": "Role of member", + "type": "string" + }, + "status": { + "description": "Status of member (Immutable)", + "type": "string" + }, + "type": { + "description": "Type of member (Immutable)", + "type": "string" + } + }, + "type": "object" + }, + "Members": { + "description": "JSON response template for List Members operation in Directory API.", + "id": "Members", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#members", + "description": "Kind of resource this is.", + "type": "string" + }, + "members": { + "description": "List of member objects.", + "items": { + "$ref": "Member" + }, + "type": "array" + }, + "nextPageToken": { + "description": "Token used to access next page of this result.", + "type": "string" + } + }, + "type": "object" + }, + "MembersHasMember": { + "description": "JSON template for Has Member response in Directory API.", + "id": "MembersHasMember", + "properties": { + "isMember": { + "description": "Identifies whether the given user is a member of the group. Membership can be direct or nested.", + "readOnly": true, + "type": "boolean" + } + }, + "type": "object" + }, + "MobileDevice": { + "description": "JSON template for Mobile Device resource in Directory API.", + "id": "MobileDevice", + "properties": { + "adbStatus": { + "description": "Adb (USB debugging) enabled or disabled on device (Read-only)", + "type": "boolean" + }, + "applications": { + "description": "List of applications installed on Mobile Device", + "items": { + "properties": { + "displayName": { + "description": "Display name of application", + "type": "string" + }, + "packageName": { + "description": "Package name of application", + "type": "string" + }, + "permission": { + "description": "List of Permissions for application", + "items": { + "type": "string" + }, + "type": "array" + }, + "versionCode": { + "description": "Version code of application", + "format": "int32", + "type": "integer" + }, + "versionName": { + "description": "Version name of application", + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + }, + "basebandVersion": { + "description": "Mobile Device Baseband version (Read-only)", + "type": "string" + }, + "bootloaderVersion": { + "description": "Mobile Device Bootloader version (Read-only)", + "type": "string" + }, + "brand": { + "description": "Mobile Device Brand (Read-only)", + "type": "string" + }, + "buildNumber": { + "description": "Mobile Device Build number (Read-only)", + "type": "string" + }, + "defaultLanguage": { + "description": "The default locale used on the Mobile Device (Read-only)", + "type": "string" + }, + "developerOptionsStatus": { + "description": "Developer options enabled or disabled on device (Read-only)", + "type": "boolean" + }, + "deviceCompromisedStatus": { + "description": "Mobile Device compromised status (Read-only)", + "type": "string" + }, + "deviceId": { + "description": "Mobile Device serial number (Read-only)", + "type": "string" + }, + "devicePasswordStatus": { + "description": "DevicePasswordStatus (Read-only)", + "type": "string" + }, + "email": { + "description": "List of owner user's email addresses (Read-only)", + "items": { + "type": "string" + }, + "type": "array" + }, + "encryptionStatus": { + "description": "Mobile Device Encryption Status (Read-only)", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "firstSync": { + "description": "Date and time the device was first synchronized with the policy settings in the G Suite administrator control panel (Read-only)", + "format": "date-time", + "type": "string" + }, + "hardware": { + "description": "Mobile Device Hardware (Read-only)", + "type": "string" + }, + "hardwareId": { + "description": "Mobile Device Hardware Id (Read-only)", + "type": "string" + }, + "imei": { + "description": "Mobile Device IMEI number (Read-only)", + "type": "string" + }, + "kernelVersion": { + "description": "Mobile Device Kernel version (Read-only)", + "type": "string" + }, + "kind": { + "default": "admin#directory#mobiledevice", + "description": "Kind of resource this is.", + "type": "string" + }, + "lastSync": { + "description": "Date and time the device was last synchronized with the policy settings in the G Suite administrator control panel (Read-only)", + "format": "date-time", + "type": "string" + }, + "managedAccountIsOnOwnerProfile": { + "description": "Boolean indicating if this account is on owner/primary profile or not (Read-only)", + "type": "boolean" + }, + "manufacturer": { + "description": "Mobile Device manufacturer (Read-only)", + "type": "string" + }, + "meid": { + "description": "Mobile Device MEID number (Read-only)", + "type": "string" + }, + "model": { + "description": "Name of the model of the device", + "type": "string" + }, + "name": { + "description": "List of owner user's names (Read-only)", + "items": { + "type": "string" + }, + "type": "array" + }, + "networkOperator": { + "description": "Mobile Device mobile or network operator (if available) (Read-only)", + "type": "string" + }, + "os": { + "description": "Name of the mobile operating system", + "type": "string" + }, + "otherAccountsInfo": { + "description": "List of accounts added on device (Read-only)", + "items": { + "type": "string" + }, + "type": "array" + }, + "privilege": { + "description": "DMAgentPermission (Read-only)", + "type": "string" + }, + "releaseVersion": { + "description": "Mobile Device release version version (Read-only)", + "type": "string" + }, + "resourceId": { + "description": "Unique identifier of Mobile Device (Read-only)", + "type": "string" + }, + "securityPatchLevel": { + "description": "Mobile Device Security patch level (Read-only)", + "format": "int64", + "type": "string" + }, + "serialNumber": { + "description": "Mobile Device SSN or Serial Number (Read-only)", + "type": "string" + }, + "status": { + "description": "Status of the device (Read-only)", + "type": "string" + }, + "supportsWorkProfile": { + "description": "Work profile supported on device (Read-only)", + "type": "boolean" + }, + "type": { + "description": "The type of device (Read-only)", + "type": "string" + }, + "unknownSourcesStatus": { + "description": "Unknown sources enabled or disabled on device (Read-only)", + "type": "boolean" + }, + "userAgent": { + "description": "Mobile Device user agent", + "type": "string" + }, + "wifiMacAddress": { + "description": "Mobile Device WiFi MAC address (Read-only)", + "type": "string" + } + }, + "type": "object" + }, + "MobileDeviceAction": { + "description": "JSON request template for firing commands on Mobile Device in Directory Devices API.", + "id": "MobileDeviceAction", + "properties": { + "action": { + "annotations": { + "required": [ + "directory.mobiledevices.action" + ] + }, + "description": "Action to be taken on the Mobile Device", + "type": "string" + } + }, + "type": "object" + }, + "MobileDevices": { + "description": "JSON response template for List Mobile Devices operation in Directory API.", + "id": "MobileDevices", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#mobiledevices", + "description": "Kind of resource this is.", + "type": "string" + }, + "mobiledevices": { + "description": "List of Mobile Device objects.", + "items": { + "$ref": "MobileDevice" + }, + "type": "array" + }, + "nextPageToken": { + "description": "Token used to access next page of this result.", + "type": "string" + } + }, + "type": "object" + }, + "Notification": { + "description": "Template for a notification resource.", + "id": "Notification", + "properties": { + "body": { + "description": "Body of the notification (Read-only)", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "fromAddress": { + "description": "Address from which the notification is received (Read-only)", + "type": "string" + }, + "isUnread": { + "annotations": { + "required": [ + "directory.notifications.patch", + "directory.notifications.update" + ] + }, + "description": "Boolean indicating whether the notification is unread or not.", + "type": "boolean" + }, + "kind": { + "default": "admin#directory#notification", + "description": "The type of the resource.", + "type": "string" + }, + "notificationId": { + "type": "string" + }, + "sendTime": { + "description": "Time at which notification was sent (Read-only)", + "format": "date-time", + "type": "string" + }, + "subject": { + "description": "Subject of the notification (Read-only)", + "type": "string" + } + }, + "type": "object" + }, + "Notifications": { + "description": "Template for notifications list response.", + "id": "Notifications", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "items": { + "description": "List of notifications in this page.", + "items": { + "$ref": "Notification" + }, + "type": "array" + }, + "kind": { + "default": "admin#directory#notifications", + "description": "The type of the resource.", + "type": "string" + }, + "nextPageToken": { + "description": "Token for fetching the next page of notifications.", + "type": "string" + }, + "unreadNotificationsCount": { + "description": "Number of unread notification for the domain.", + "format": "int32", + "type": "integer" + } + }, + "type": "object" + }, + "OrgUnit": { + "description": "JSON template for Org Unit resource in Directory API.", + "id": "OrgUnit", + "properties": { + "blockInheritance": { + "description": "Should block inheritance", + "type": "boolean" + }, + "description": { + "description": "Description of OrgUnit", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#orgUnit", + "description": "Kind of resource this is.", + "type": "string" + }, + "name": { + "annotations": { + "required": [ + "directory.orgunits.insert" + ] + }, + "description": "Name of OrgUnit", + "type": "string" + }, + "orgUnitId": { + "description": "Id of OrgUnit", + "type": "string" + }, + "orgUnitPath": { + "description": "Path of OrgUnit", + "type": "string" + }, + "parentOrgUnitId": { + "description": "Id of parent OrgUnit", + "type": "string" + }, + "parentOrgUnitPath": { + "description": "Path of parent OrgUnit", + "type": "string" + } + }, + "type": "object" + }, + "OrgUnits": { + "description": "JSON response template for List Organization Units operation in Directory API.", + "id": "OrgUnits", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#orgUnits", + "description": "Kind of resource this is.", + "type": "string" + }, + "organizationUnits": { + "description": "List of user objects.", + "items": { + "$ref": "OrgUnit" + }, + "type": "array" + } + }, + "type": "object" + }, + "Privilege": { + "description": "JSON template for privilege resource in Directory API.", + "id": "Privilege", + "properties": { + "childPrivileges": { + "description": "A list of child privileges. Privileges for a service form a tree. Each privilege can have a list of child privileges; this list is empty for a leaf privilege.", + "items": { + "$ref": "Privilege" + }, + "type": "array" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "isOuScopable": { + "description": "If the privilege can be restricted to an organization unit.", + "type": "boolean" + }, + "kind": { + "default": "admin#directory#privilege", + "description": "The type of the API resource. This is always admin#directory#privilege.", + "type": "string" + }, + "privilegeName": { + "description": "The name of the privilege.", + "type": "string" + }, + "serviceId": { + "description": "The obfuscated ID of the service this privilege is for. This value is returned with Privileges.list().", + "type": "string" + }, + "serviceName": { + "description": "The name of the service this privilege is for.", + "type": "string" + } + }, + "type": "object" + }, + "Privileges": { + "description": "JSON response template for List privileges operation in Directory API.", + "id": "Privileges", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "items": { + "description": "A list of Privilege resources.", + "items": { + "$ref": "Privilege" + }, + "type": "array" + }, + "kind": { + "default": "admin#directory#privileges", + "description": "The type of the API resource. This is always admin#directory#privileges.", + "type": "string" + } + }, + "type": "object" + }, + "Role": { + "description": "JSON template for role resource in Directory API.", + "id": "Role", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "isSuperAdminRole": { + "description": "Returns true if the role is a super admin role.", + "type": "boolean" + }, + "isSystemRole": { + "description": "Returns true if this is a pre-defined system role.", + "type": "boolean" + }, + "kind": { + "default": "admin#directory#role", + "description": "The type of the API resource. This is always admin#directory#role.", + "type": "string" + }, + "roleDescription": { + "description": "A short description of the role.", + "type": "string" + }, + "roleId": { + "description": "ID of the role.", + "format": "int64", + "type": "string" + }, + "roleName": { + "annotations": { + "required": [ + "directory.roles.insert" + ] + }, + "description": "Name of the role.", + "type": "string" + }, + "rolePrivileges": { + "annotations": { + "required": [ + "directory.roles.insert" + ] + }, + "description": "The set of privileges that are granted to this role.", + "items": { + "properties": { + "privilegeName": { + "description": "The name of the privilege.", + "type": "string" + }, + "serviceId": { + "description": "The obfuscated ID of the service this privilege is for. This value is returned with Privileges.list().", + "type": "string" + } + }, + "type": "object" + }, + "type": "array" + } + }, + "type": "object" + }, + "RoleAssignment": { + "description": "JSON template for roleAssignment resource in Directory API.", + "id": "RoleAssignment", + "properties": { + "assignedTo": { + "description": "The unique ID of the user this role is assigned to.", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#roleAssignment", + "description": "The type of the API resource. This is always admin#directory#roleAssignment.", + "type": "string" + }, + "orgUnitId": { + "description": "If the role is restricted to an organization unit, this contains the ID for the organization unit the exercise of this role is restricted to.", + "type": "string" + }, + "roleAssignmentId": { + "description": "ID of this roleAssignment.", + "format": "int64", + "type": "string" + }, + "roleId": { + "description": "The ID of the role that is assigned.", + "format": "int64", + "type": "string" + }, + "scopeType": { + "description": "The scope in which this role is assigned. Possible values are: \n- CUSTOMER\n- ORG_UNIT", + "type": "string" + } + }, + "type": "object" + }, + "RoleAssignments": { + "description": "JSON response template for List roleAssignments operation in Directory API.", + "id": "RoleAssignments", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "items": { + "description": "A list of RoleAssignment resources.", + "items": { + "$ref": "RoleAssignment" + }, + "type": "array" + }, + "kind": { + "default": "admin#directory#roleAssignments", + "description": "The type of the API resource. This is always admin#directory#roleAssignments.", + "type": "string" + }, + "nextPageToken": { + "type": "string" + } + }, + "type": "object" + }, + "Roles": { + "description": "JSON response template for List roles operation in Directory API.", + "id": "Roles", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "items": { + "description": "A list of Role resources.", + "items": { + "$ref": "Role" + }, + "type": "array" + }, + "kind": { + "default": "admin#directory#roles", + "description": "The type of the API resource. This is always admin#directory#roles.", + "type": "string" + }, + "nextPageToken": { + "type": "string" + } + }, + "type": "object" + }, + "Schema": { + "description": "JSON template for Schema resource in Directory API.", + "id": "Schema", + "properties": { + "displayName": { + "annotations": { + "required": [ + "directory.schemas.insert" + ] + }, + "description": "Display name for the schema.", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "fields": { + "annotations": { + "required": [ + "directory.schemas.insert", + "directory.schemas.update" + ] + }, + "description": "Fields of Schema", + "items": { + "$ref": "SchemaFieldSpec" + }, + "type": "array" + }, + "kind": { + "default": "admin#directory#schema", + "description": "Kind of resource this is.", + "type": "string" + }, + "schemaId": { + "description": "Unique identifier of Schema (Read-only)", + "type": "string" + }, + "schemaName": { + "annotations": { + "required": [ + "directory.schemas.insert" + ] + }, + "description": "Schema name", + "type": "string" + } + }, + "type": "object" + }, + "SchemaFieldSpec": { + "description": "JSON template for FieldSpec resource for Schemas in Directory API.", + "id": "SchemaFieldSpec", + "properties": { + "displayName": { + "annotations": { + "required": [ + "directory.schemas.insert", + "directory.schemas.update" + ] + }, + "description": "Display Name of the field.", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "fieldId": { + "description": "Unique identifier of Field (Read-only)", + "type": "string" + }, + "fieldName": { + "annotations": { + "required": [ + "directory.schemas.insert", + "directory.schemas.update" + ] + }, + "description": "Name of the field.", + "type": "string" + }, + "fieldType": { + "annotations": { + "required": [ + "directory.schemas.insert", + "directory.schemas.update" + ] + }, + "description": "Type of the field.", + "type": "string" + }, + "indexed": { + "default": "true", + "description": "Boolean specifying whether the field is indexed or not.", + "type": "boolean" + }, + "kind": { + "default": "admin#directory#schema#fieldspec", + "description": "Kind of resource this is.", + "type": "string" + }, + "multiValued": { + "description": "Boolean specifying whether this is a multi-valued field or not.", + "type": "boolean" + }, + "numericIndexingSpec": { + "description": "Indexing spec for a numeric field. By default, only exact match queries will be supported for numeric fields. Setting the numericIndexingSpec allows range queries to be supported.", + "properties": { + "maxValue": { + "description": "Maximum value of this field. This is meant to be indicative rather than enforced. Values outside this range will still be indexed, but search may not be as performant.", + "format": "double", + "type": "number" + }, + "minValue": { + "description": "Minimum value of this field. This is meant to be indicative rather than enforced. Values outside this range will still be indexed, but search may not be as performant.", + "format": "double", + "type": "number" + } + }, + "type": "object" + }, + "readAccessType": { + "default": "ALL_DOMAIN_USERS", + "description": "Read ACLs on the field specifying who can view values of this field. Valid values are \"ALL_DOMAIN_USERS\" and \"ADMINS_AND_SELF\".", + "type": "string" + } + }, + "type": "object" + }, + "Schemas": { + "description": "JSON response template for List Schema operation in Directory API.", + "id": "Schemas", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#schemas", + "description": "Kind of resource this is.", + "type": "string" + }, + "schemas": { + "description": "List of UserSchema objects.", + "items": { + "$ref": "Schema" + }, + "type": "array" + } + }, + "type": "object" + }, + "Token": { + "description": "JSON template for token resource in Directory API.", + "id": "Token", + "properties": { + "anonymous": { + "description": "Whether the application is registered with Google. The value is true if the application has an anonymous Client ID.", + "type": "boolean" + }, + "clientId": { + "description": "The Client ID of the application the token is issued to.", + "type": "string" + }, + "displayText": { + "description": "The displayable name of the application the token is issued to.", + "type": "string" + }, + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#token", + "description": "The type of the API resource. This is always admin#directory#token.", + "type": "string" + }, + "nativeApp": { + "description": "Whether the token is issued to an installed application. The value is true if the application is installed to a desktop or mobile device.", + "type": "boolean" + }, + "scopes": { + "description": "A list of authorization scopes the application is granted.", + "items": { + "type": "string" + }, + "type": "array" + }, + "userKey": { + "description": "The unique ID of the user that issued the token.", + "type": "string" + } + }, + "type": "object" + }, + "Tokens": { + "description": "JSON response template for List tokens operation in Directory API.", + "id": "Tokens", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "items": { + "description": "A list of Token resources.", + "items": { + "$ref": "Token" + }, + "type": "array" + }, + "kind": { + "default": "admin#directory#tokenList", + "description": "The type of the API resource. This is always admin#directory#tokenList.", + "type": "string" + } + }, + "type": "object" + }, + "TrustedAppId": { + "description": "JSON template for Trusted App Ids Resource object in Directory API.", + "id": "TrustedAppId", + "properties": { + "androidPackageName": { + "description": "Android package name.", + "type": "string" + }, + "certificateHashSHA1": { + "description": "SHA1 signature of the app certificate.", + "type": "string" + }, + "certificateHashSHA256": { + "description": "SHA256 signature of the app certificate.", + "type": "string" + }, + "etag": { + "type": "string" + }, + "kind": { + "default": "admin#directory#trustedappid", + "description": "Identifies the resource as a trusted AppId.", + "type": "string" + } + }, + "type": "object" + }, + "TrustedApps": { + "description": "JSON template for Trusted Apps response object of a user in Directory API.", + "id": "TrustedApps", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#trustedapplist", + "description": "Identifies the resource as trusted apps response.", + "type": "string" + }, + "nextPageToken": { + "type": "string" + }, + "trustedApps": { + "description": "Trusted Apps list.", + "items": { + "$ref": "TrustedAppId" + }, + "type": "array" + } + }, + "type": "object" + }, + "User": { + "description": "JSON template for User object in Directory API.", + "id": "User", + "properties": { + "addresses": { + "type": "any" + }, + "agreedToTerms": { + "description": "Indicates if user has agreed to terms (Read-only)", + "readOnly": true, + "type": "boolean" + }, + "aliases": { + "description": "List of aliases (Read-only)", + "items": { + "type": "string" + }, + "readOnly": true, + "type": "array" + }, + "archived": { + "description": "Indicates if user is archived.", + "type": "boolean" + }, + "changePasswordAtNextLogin": { + "description": "Boolean indicating if the user should change password in next login", + "type": "boolean" + }, + "creationTime": { + "description": "User's G Suite account creation time. (Read-only)", + "format": "date-time", + "readOnly": true, + "type": "string" + }, + "customSchemas": { + "additionalProperties": { + "$ref": "UserCustomProperties" + }, + "description": "Custom fields of the user.", + "type": "object" + }, + "customerId": { + "description": "CustomerId of User (Read-only)", + "readOnly": true, + "type": "string" + }, + "deletionTime": { + "format": "date-time", + "readOnly": true, + "type": "string" + }, + "emails": { + "type": "any" + }, + "etag": { + "description": "ETag of the resource.", + "readOnly": true, + "type": "string" + }, + "externalIds": { + "type": "any" + }, + "gender": { + "type": "any" + }, + "hashFunction": { + "description": "Hash function name for password. Supported are MD5, SHA-1 and crypt", + "type": "string" + }, + "id": { + "description": "Unique identifier of User (Read-only)", + "type": "string" + }, + "ims": { + "type": "any" + }, + "includeInGlobalAddressList": { + "description": "Boolean indicating if user is included in Global Address List", + "type": "boolean" + }, + "ipWhitelisted": { + "description": "Boolean indicating if ip is whitelisted", + "type": "boolean" + }, + "isAdmin": { + "description": "Boolean indicating if the user is admin (Read-only)", + "readOnly": true, + "type": "boolean" + }, + "isDelegatedAdmin": { + "description": "Boolean indicating if the user is delegated admin (Read-only)", + "readOnly": true, + "type": "boolean" + }, + "isEnforcedIn2Sv": { + "description": "Is 2-step verification enforced (Read-only)", + "readOnly": true, + "type": "boolean" + }, + "isEnrolledIn2Sv": { + "description": "Is enrolled in 2-step verification (Read-only)", + "readOnly": true, + "type": "boolean" + }, + "isMailboxSetup": { + "description": "Is mailbox setup (Read-only)", + "readOnly": true, + "type": "boolean" + }, + "keywords": { + "type": "any" + }, + "kind": { + "default": "admin#directory#user", + "description": "Kind of resource this is.", + "readOnly": true, + "type": "string" + }, + "languages": { + "type": "any" + }, + "lastLoginTime": { + "description": "User's last login time. (Read-only)", + "format": "date-time", + "readOnly": true, + "type": "string" + }, + "locations": { + "type": "any" + }, + "name": { + "$ref": "UserName", + "annotations": { + "required": [ + "directory.users.insert" + ] + }, + "description": "User's name" + }, + "nonEditableAliases": { + "description": "List of non editable aliases (Read-only)", + "items": { + "type": "string" + }, + "readOnly": true, + "type": "array" + }, + "notes": { + "type": "any" + }, + "orgUnitPath": { + "description": "OrgUnit of User", + "type": "string" + }, + "organizations": { + "type": "any" + }, + "password": { + "annotations": { + "required": [ + "directory.users.insert" + ] + }, + "description": "User's password", + "type": "string" + }, + "phones": { + "type": "any" + }, + "posixAccounts": { + "type": "any" + }, + "primaryEmail": { + "annotations": { + "required": [ + "directory.users.insert" + ] + }, + "description": "username of User", + "type": "string" + }, + "recoveryEmail": { + "description": "Recovery email of the user.", + "type": "string" + }, + "recoveryPhone": { + "description": "Recovery phone of the user. The phone number must be in the E.164 format, starting with the plus sign (+). Example: +16506661212.", + "type": "string" + }, + "relations": { + "type": "any" + }, + "sshPublicKeys": { + "type": "any" + }, + "suspended": { + "description": "Indicates if user is suspended.", + "type": "boolean" + }, + "suspensionReason": { + "description": "Suspension reason if user is suspended (Read-only)", + "readOnly": true, + "type": "string" + }, + "thumbnailPhotoEtag": { + "description": "ETag of the user's photo (Read-only)", + "readOnly": true, + "type": "string" + }, + "thumbnailPhotoUrl": { + "description": "Photo Url of the user (Read-only)", + "readOnly": true, + "type": "string" + }, + "websites": { + "type": "any" + } + }, + "type": "object" + }, + "UserAbout": { + "description": "JSON template for About (notes) of a user in Directory API.", + "id": "UserAbout", + "properties": { + "contentType": { + "description": "About entry can have a type which indicates the content type. It can either be plain or html. By default, notes contents are assumed to contain plain text.", + "type": "string" + }, + "value": { + "description": "Actual value of notes.", + "type": "string" + } + }, + "type": "object" + }, + "UserAddress": { + "description": "JSON template for address.", + "id": "UserAddress", + "properties": { + "country": { + "description": "Country.", + "type": "string" + }, + "countryCode": { + "description": "Country code.", + "type": "string" + }, + "customType": { + "description": "Custom type.", + "type": "string" + }, + "extendedAddress": { + "description": "Extended Address.", + "type": "string" + }, + "formatted": { + "description": "Formatted address.", + "type": "string" + }, + "locality": { + "description": "Locality.", + "type": "string" + }, + "poBox": { + "description": "Other parts of address.", + "type": "string" + }, + "postalCode": { + "description": "Postal code.", + "type": "string" + }, + "primary": { + "description": "If this is user's primary address. Only one entry could be marked as primary.", + "type": "boolean" + }, + "region": { + "description": "Region.", + "type": "string" + }, + "sourceIsStructured": { + "description": "User supplied address was structured. Structured addresses are NOT supported at this time. You might be able to write structured addresses, but any values will eventually be clobbered.", + "type": "boolean" + }, + "streetAddress": { + "description": "Street.", + "type": "string" + }, + "type": { + "description": "Each entry can have a type which indicates standard values of that entry. For example address could be of home, work etc. In addition to the standard type, an entry can have a custom type and can take any value. Such type should have the CUSTOM value as type and also have a customType value.", + "type": "string" + } + }, + "type": "object" + }, + "UserCustomProperties": { + "additionalProperties": { + "type": "any" + }, + "description": "JSON template for a set of custom properties (i.e. all fields in a particular schema)", + "id": "UserCustomProperties", + "type": "object" + }, + "UserEmail": { + "description": "JSON template for an email.", + "id": "UserEmail", + "properties": { + "address": { + "description": "Email id of the user.", + "type": "string" + }, + "customType": { + "description": "Custom Type.", + "type": "string" + }, + "primary": { + "description": "If this is user's primary email. Only one entry could be marked as primary.", + "type": "boolean" + }, + "type": { + "description": "Each entry can have a type which indicates standard types of that entry. For example email could be of home, work etc. In addition to the standard type, an entry can have a custom type and can take any value Such types should have the CUSTOM value as type and also have a customType value.", + "type": "string" + } + }, + "type": "object" + }, + "UserExternalId": { + "description": "JSON template for an externalId entry.", + "id": "UserExternalId", + "properties": { + "customType": { + "description": "Custom type.", + "type": "string" + }, + "type": { + "description": "The type of the Id.", + "type": "string" + }, + "value": { + "description": "The value of the id.", + "type": "string" + } + }, + "type": "object" + }, + "UserGender": { + "id": "UserGender", + "properties": { + "addressMeAs": { + "description": "AddressMeAs. A human-readable string containing the proper way to refer to the profile owner by humans, for example \"he/him/his\" or \"they/them/their\".", + "type": "string" + }, + "customGender": { + "description": "Custom gender.", + "type": "string" + }, + "type": { + "description": "Gender.", + "type": "string" + } + }, + "type": "object" + }, + "UserIm": { + "description": "JSON template for instant messenger of an user.", + "id": "UserIm", + "properties": { + "customProtocol": { + "description": "Custom protocol.", + "type": "string" + }, + "customType": { + "description": "Custom type.", + "type": "string" + }, + "im": { + "description": "Instant messenger id.", + "type": "string" + }, + "primary": { + "description": "If this is user's primary im. Only one entry could be marked as primary.", + "type": "boolean" + }, + "protocol": { + "description": "Protocol used in the instant messenger. It should be one of the values from ImProtocolTypes map. Similar to type, it can take a CUSTOM value and specify the custom name in customProtocol field.", + "type": "string" + }, + "type": { + "description": "Each entry can have a type which indicates standard types of that entry. For example instant messengers could be of home, work etc. In addition to the standard type, an entry can have a custom type and can take any value. Such types should have the CUSTOM value as type and also have a customType value.", + "type": "string" + } + }, + "type": "object" + }, + "UserKeyword": { + "description": "JSON template for a keyword entry.", + "id": "UserKeyword", + "properties": { + "customType": { + "description": "Custom Type.", + "type": "string" + }, + "type": { + "description": "Each entry can have a type which indicates standard type of that entry. For example, keyword could be of type occupation or outlook. In addition to the standard type, an entry can have a custom type and can give it any name. Such types should have the CUSTOM value as type and also have a customType value.", + "type": "string" + }, + "value": { + "description": "Keyword.", + "type": "string" + } + }, + "type": "object" + }, + "UserLanguage": { + "description": "JSON template for a language entry.", + "id": "UserLanguage", + "properties": { + "customLanguage": { + "description": "Other language. User can provide own language name if there is no corresponding Google III language code. If this is set LanguageCode can't be set", + "type": "string" + }, + "languageCode": { + "description": "Language Code. Should be used for storing Google III LanguageCode string representation for language. Illegal values cause SchemaException.", + "type": "string" + } + }, + "type": "object" + }, + "UserLocation": { + "description": "JSON template for a location entry.", + "id": "UserLocation", + "properties": { + "area": { + "description": "Textual location. This is most useful for display purposes to concisely describe the location. For example, \"Mountain View, CA\", \"Near Seattle\", \"US-NYC-9TH 9A209A\".", + "type": "string" + }, + "buildingId": { + "description": "Building Identifier.", + "type": "string" + }, + "customType": { + "description": "Custom Type.", + "type": "string" + }, + "deskCode": { + "description": "Most specific textual code of individual desk location.", + "type": "string" + }, + "floorName": { + "description": "Floor name/number.", + "type": "string" + }, + "floorSection": { + "description": "Floor section. More specific location within the floor. For example, if a floor is divided into sections \"A\", \"B\", and \"C\", this field would identify one of those values.", + "type": "string" + }, + "type": { + "description": "Each entry can have a type which indicates standard types of that entry. For example location could be of types default and desk. In addition to standard type, an entry can have a custom type and can give it any name. Such types should have \"custom\" as type and also have a customType value.", + "type": "string" + } + }, + "type": "object" + }, + "UserMakeAdmin": { + "description": "JSON request template for setting/revoking admin status of a user in Directory API.", + "id": "UserMakeAdmin", + "properties": { + "status": { + "annotations": { + "required": [ + "directory.users.makeAdmin" + ] + }, + "description": "Boolean indicating new admin status of the user", + "type": "boolean" + } + }, + "type": "object" + }, + "UserName": { + "description": "JSON template for name of a user in Directory API.", + "id": "UserName", + "properties": { + "familyName": { + "annotations": { + "required": [ + "directory.users.insert" + ] + }, + "description": "Last Name", + "type": "string" + }, + "fullName": { + "description": "Full Name", + "type": "string" + }, + "givenName": { + "annotations": { + "required": [ + "directory.users.insert" + ] + }, + "description": "First Name", + "type": "string" + } + }, + "type": "object" + }, + "UserOrganization": { + "description": "JSON template for an organization entry.", + "id": "UserOrganization", + "properties": { + "costCenter": { + "description": "The cost center of the users department.", + "type": "string" + }, + "customType": { + "description": "Custom type.", + "type": "string" + }, + "department": { + "description": "Department within the organization.", + "type": "string" + }, + "description": { + "description": "Description of the organization.", + "type": "string" + }, + "domain": { + "description": "The domain to which the organization belongs to.", + "type": "string" + }, + "fullTimeEquivalent": { + "description": "The full-time equivalent millipercent within the organization (100000 = 100%).", + "format": "int32", + "type": "integer" + }, + "location": { + "description": "Location of the organization. This need not be fully qualified address.", + "type": "string" + }, + "name": { + "description": "Name of the organization", + "type": "string" + }, + "primary": { + "description": "If it user's primary organization.", + "type": "boolean" + }, + "symbol": { + "description": "Symbol of the organization.", + "type": "string" + }, + "title": { + "description": "Title (designation) of the user in the organization.", + "type": "string" + }, + "type": { + "description": "Each entry can have a type which indicates standard types of that entry. For example organization could be of school, work etc. In addition to the standard type, an entry can have a custom type and can give it any name. Such types should have the CUSTOM value as type and also have a CustomType value.", + "type": "string" + } + }, + "type": "object" + }, + "UserPhone": { + "description": "JSON template for a phone entry.", + "id": "UserPhone", + "properties": { + "customType": { + "description": "Custom Type.", + "type": "string" + }, + "primary": { + "description": "If this is user's primary phone or not.", + "type": "boolean" + }, + "type": { + "description": "Each entry can have a type which indicates standard types of that entry. For example phone could be of home_fax, work, mobile etc. In addition to the standard type, an entry can have a custom type and can give it any name. Such types should have the CUSTOM value as type and also have a customType value.", + "type": "string" + }, + "value": { + "description": "Phone number.", + "type": "string" + } + }, + "type": "object" + }, + "UserPhoto": { + "description": "JSON template for Photo object in Directory API.", + "id": "UserPhoto", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "height": { + "description": "Height in pixels of the photo", + "format": "int32", + "type": "integer" + }, + "id": { + "description": "Unique identifier of User (Read-only)", + "type": "string" + }, + "kind": { + "default": "admin#directory#user#photo", + "description": "Kind of resource this is.", + "type": "string" + }, + "mimeType": { + "description": "Mime Type of the photo", + "type": "string" + }, + "photoData": { + "annotations": { + "required": [ + "directory.users.photos.update" + ] + }, + "description": "Base64 encoded photo data", + "format": "byte", + "type": "string" + }, + "primaryEmail": { + "description": "Primary email of User (Read-only)", + "type": "string" + }, + "width": { + "description": "Width in pixels of the photo", + "format": "int32", + "type": "integer" + } + }, + "type": "object" + }, + "UserPosixAccount": { + "description": "JSON template for a POSIX account entry. Description of the field family: go/fbs-posix.", + "id": "UserPosixAccount", + "properties": { + "accountId": { + "description": "A POSIX account field identifier.", + "type": "string" + }, + "gecos": { + "description": "The GECOS (user information) for this account.", + "type": "string" + }, + "gid": { + "description": "The default group ID.", + "format": "uint64", + "type": "string" + }, + "homeDirectory": { + "description": "The path to the home directory for this account.", + "type": "string" + }, + "operatingSystemType": { + "description": "The operating system type for this account.", + "type": "string" + }, + "primary": { + "description": "If this is user's primary account within the SystemId.", + "type": "boolean" + }, + "shell": { + "description": "The path to the login shell for this account.", + "type": "string" + }, + "systemId": { + "description": "System identifier for which account Username or Uid apply to.", + "type": "string" + }, + "uid": { + "description": "The POSIX compliant user ID.", + "format": "uint64", + "type": "string" + }, + "username": { + "description": "The username of the account.", + "type": "string" + } + }, + "type": "object" + }, + "UserRelation": { + "description": "JSON template for a relation entry.", + "id": "UserRelation", + "properties": { + "customType": { + "description": "Custom Type.", + "type": "string" + }, + "type": { + "description": "The relation of the user. Some of the possible values are mother, father, sister, brother, manager, assistant, partner.", + "type": "string" + }, + "value": { + "description": "The name of the relation.", + "type": "string" + } + }, + "type": "object" + }, + "UserSshPublicKey": { + "description": "JSON template for a POSIX account entry.", + "id": "UserSshPublicKey", + "properties": { + "expirationTimeUsec": { + "description": "An expiration time in microseconds since epoch.", + "format": "int64", + "type": "string" + }, + "fingerprint": { + "description": "A SHA-256 fingerprint of the SSH public key. (Read-only)", + "readOnly": true, + "type": "string" + }, + "key": { + "description": "An SSH public key.", + "type": "string" + } + }, + "type": "object" + }, + "UserUndelete": { + "description": "JSON request template to undelete a user in Directory API.", + "id": "UserUndelete", + "properties": { + "orgUnitPath": { + "description": "OrgUnit of User", + "type": "string" + } + }, + "type": "object" + }, + "UserWebsite": { + "description": "JSON template for a website entry.", + "id": "UserWebsite", + "properties": { + "customType": { + "description": "Custom Type.", + "type": "string" + }, + "primary": { + "description": "If this is user's primary website or not.", + "type": "boolean" + }, + "type": { + "description": "Each entry can have a type which indicates standard types of that entry. For example website could be of home, work, blog etc. In addition to the standard type, an entry can have a custom type and can give it any name. Such types should have the CUSTOM value as type and also have a customType value.", + "type": "string" + }, + "value": { + "description": "Website.", + "type": "string" + } + }, + "type": "object" + }, + "Users": { + "description": "JSON response template for List Users operation in Apps Directory API.", + "id": "Users", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#users", + "description": "Kind of resource this is.", + "type": "string" + }, + "nextPageToken": { + "description": "Token used to access next page of this result.", + "type": "string" + }, + "trigger_event": { + "description": "Event that triggered this response (only used in case of Push Response)", + "type": "string" + }, + "users": { + "description": "List of user objects.", + "items": { + "$ref": "User" + }, + "type": "array" + } + }, + "type": "object" + }, + "VerificationCode": { + "description": "JSON template for verification codes in Directory API.", + "id": "VerificationCode", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "kind": { + "default": "admin#directory#verificationCode", + "description": "The type of the resource. This is always admin#directory#verificationCode.", + "type": "string" + }, + "userId": { + "description": "The obfuscated unique ID of the user.", + "type": "string" + }, + "verificationCode": { + "description": "A current verification code for the user. Invalidated or used verification codes are not returned as part of the result.", + "type": "string" + } + }, + "type": "object" + }, + "VerificationCodes": { + "description": "JSON response template for List verification codes operation in Directory API.", + "id": "VerificationCodes", + "properties": { + "etag": { + "description": "ETag of the resource.", + "type": "string" + }, + "items": { + "description": "A list of verification code resources.", + "items": { + "$ref": "VerificationCode" + }, + "type": "array" + }, + "kind": { + "default": "admin#directory#verificationCodesList", + "description": "The type of the resource. This is always admin#directory#verificationCodesList.", + "type": "string" + } + }, + "type": "object" + } + }, + "servicePath": "admin/directory/v1/", + "title": "Admin Directory API", + "version": "directory_v1" +} \ No newline at end of file diff --git a/vendor/google.golang.org/api/admin/directory/v1/admin-gen.go b/vendor/google.golang.org/api/admin/directory/v1/admin-gen.go new file mode 100644 index 00000000..7aa90f57 --- /dev/null +++ b/vendor/google.golang.org/api/admin/directory/v1/admin-gen.go @@ -0,0 +1,21696 @@ +// Copyright 2019 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated file. DO NOT EDIT. + +// Package admin provides access to the Admin Directory API. +// +// For product documentation, see: https://developers.google.com/admin-sdk/directory/ +// +// Creating a client +// +// Usage example: +// +// import "google.golang.org/api/admin/directory/v1" +// ... +// ctx := context.Background() +// adminService, err := admin.NewService(ctx) +// +// In this example, Google Application Default Credentials are used for authentication. +// +// For information on how to create and obtain Application Default Credentials, see https://developers.google.com/identity/protocols/application-default-credentials. +// +// Other authentication options +// +// By default, all available scopes (see "Constants") are used to authenticate. To restrict scopes, use option.WithScopes: +// +// adminService, err := admin.NewService(ctx, option.WithScopes(admin.AdminDirectoryUserschemaReadonlyScope)) +// +// To use an API key for authentication (note: some APIs do not support API keys), use option.WithAPIKey: +// +// adminService, err := admin.NewService(ctx, option.WithAPIKey("AIza...")) +// +// To use an OAuth token (e.g., a user token obtained via a three-legged OAuth flow), use option.WithTokenSource: +// +// config := &oauth2.Config{...} +// // ... +// token, err := config.Exchange(ctx, ...) +// adminService, err := admin.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token))) +// +// See https://godoc.org/google.golang.org/api/option/ for details on options. +package admin // import "google.golang.org/api/admin/directory/v1" + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + + gensupport "google.golang.org/api/gensupport" + googleapi "google.golang.org/api/googleapi" + option "google.golang.org/api/option" + htransport "google.golang.org/api/transport/http" +) + +// Always reference these packages, just in case the auto-generated code +// below doesn't. +var _ = bytes.NewBuffer +var _ = strconv.Itoa +var _ = fmt.Sprintf +var _ = json.NewDecoder +var _ = io.Copy +var _ = url.Parse +var _ = gensupport.MarshalJSON +var _ = googleapi.Version +var _ = errors.New +var _ = strings.Replace +var _ = context.Canceled + +const apiId = "admin:directory_v1" +const apiName = "admin" +const apiVersion = "directory_v1" +const basePath = "https://www.googleapis.com/admin/directory/v1/" + +// OAuth2 scopes used by this API. +const ( + // View and manage customer related information + AdminDirectoryCustomerScope = "https://www.googleapis.com/auth/admin.directory.customer" + + // View customer related information + AdminDirectoryCustomerReadonlyScope = "https://www.googleapis.com/auth/admin.directory.customer.readonly" + + // View and manage your Chrome OS devices' metadata + AdminDirectoryDeviceChromeosScope = "https://www.googleapis.com/auth/admin.directory.device.chromeos" + + // View your Chrome OS devices' metadata + AdminDirectoryDeviceChromeosReadonlyScope = "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly" + + // View and manage your mobile devices' metadata + AdminDirectoryDeviceMobileScope = "https://www.googleapis.com/auth/admin.directory.device.mobile" + + // Manage your mobile devices by performing administrative tasks + AdminDirectoryDeviceMobileActionScope = "https://www.googleapis.com/auth/admin.directory.device.mobile.action" + + // View your mobile devices' metadata + AdminDirectoryDeviceMobileReadonlyScope = "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly" + + // View and manage the provisioning of domains for your customers + AdminDirectoryDomainScope = "https://www.googleapis.com/auth/admin.directory.domain" + + // View domains related to your customers + AdminDirectoryDomainReadonlyScope = "https://www.googleapis.com/auth/admin.directory.domain.readonly" + + // View and manage the provisioning of groups on your domain + AdminDirectoryGroupScope = "https://www.googleapis.com/auth/admin.directory.group" + + // View and manage group subscriptions on your domain + AdminDirectoryGroupMemberScope = "https://www.googleapis.com/auth/admin.directory.group.member" + + // View group subscriptions on your domain + AdminDirectoryGroupMemberReadonlyScope = "https://www.googleapis.com/auth/admin.directory.group.member.readonly" + + // View groups on your domain + AdminDirectoryGroupReadonlyScope = "https://www.googleapis.com/auth/admin.directory.group.readonly" + + // View and manage notifications received on your domain + AdminDirectoryNotificationsScope = "https://www.googleapis.com/auth/admin.directory.notifications" + + // View and manage organization units on your domain + AdminDirectoryOrgunitScope = "https://www.googleapis.com/auth/admin.directory.orgunit" + + // View organization units on your domain + AdminDirectoryOrgunitReadonlyScope = "https://www.googleapis.com/auth/admin.directory.orgunit.readonly" + + // View and manage the provisioning of calendar resources on your domain + AdminDirectoryResourceCalendarScope = "https://www.googleapis.com/auth/admin.directory.resource.calendar" + + // View calendar resources on your domain + AdminDirectoryResourceCalendarReadonlyScope = "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" + + // Manage delegated admin roles for your domain + AdminDirectoryRolemanagementScope = "https://www.googleapis.com/auth/admin.directory.rolemanagement" + + // View delegated admin roles for your domain + AdminDirectoryRolemanagementReadonlyScope = "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" + + // View and manage the provisioning of users on your domain + AdminDirectoryUserScope = "https://www.googleapis.com/auth/admin.directory.user" + + // View and manage user aliases on your domain + AdminDirectoryUserAliasScope = "https://www.googleapis.com/auth/admin.directory.user.alias" + + // View user aliases on your domain + AdminDirectoryUserAliasReadonlyScope = "https://www.googleapis.com/auth/admin.directory.user.alias.readonly" + + // View users on your domain + AdminDirectoryUserReadonlyScope = "https://www.googleapis.com/auth/admin.directory.user.readonly" + + // Manage data access permissions for users on your domain + AdminDirectoryUserSecurityScope = "https://www.googleapis.com/auth/admin.directory.user.security" + + // View and manage the provisioning of user schemas on your domain + AdminDirectoryUserschemaScope = "https://www.googleapis.com/auth/admin.directory.userschema" + + // View user schemas on your domain + AdminDirectoryUserschemaReadonlyScope = "https://www.googleapis.com/auth/admin.directory.userschema.readonly" +) + +// NewService creates a new Service. +func NewService(ctx context.Context, opts ...option.ClientOption) (*Service, error) { + scopesOption := option.WithScopes( + "https://www.googleapis.com/auth/admin.directory.customer", + "https://www.googleapis.com/auth/admin.directory.customer.readonly", + "https://www.googleapis.com/auth/admin.directory.device.chromeos", + "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly", + "https://www.googleapis.com/auth/admin.directory.device.mobile", + "https://www.googleapis.com/auth/admin.directory.device.mobile.action", + "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly", + "https://www.googleapis.com/auth/admin.directory.domain", + "https://www.googleapis.com/auth/admin.directory.domain.readonly", + "https://www.googleapis.com/auth/admin.directory.group", + "https://www.googleapis.com/auth/admin.directory.group.member", + "https://www.googleapis.com/auth/admin.directory.group.member.readonly", + "https://www.googleapis.com/auth/admin.directory.group.readonly", + "https://www.googleapis.com/auth/admin.directory.notifications", + "https://www.googleapis.com/auth/admin.directory.orgunit", + "https://www.googleapis.com/auth/admin.directory.orgunit.readonly", + "https://www.googleapis.com/auth/admin.directory.resource.calendar", + "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly", + "https://www.googleapis.com/auth/admin.directory.rolemanagement", + "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly", + "https://www.googleapis.com/auth/admin.directory.user", + "https://www.googleapis.com/auth/admin.directory.user.alias", + "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", + "https://www.googleapis.com/auth/admin.directory.user.readonly", + "https://www.googleapis.com/auth/admin.directory.user.security", + "https://www.googleapis.com/auth/admin.directory.userschema", + "https://www.googleapis.com/auth/admin.directory.userschema.readonly", + ) + // NOTE: prepend, so we don't override user-specified scopes. + opts = append([]option.ClientOption{scopesOption}, opts...) + client, endpoint, err := htransport.NewClient(ctx, opts...) + if err != nil { + return nil, err + } + s, err := New(client) + if err != nil { + return nil, err + } + if endpoint != "" { + s.BasePath = endpoint + } + return s, nil +} + +// New creates a new Service. It uses the provided http.Client for requests. +// +// Deprecated: please use NewService instead. +// To provide a custom HTTP client, use option.WithHTTPClient. +// If you are using google.golang.org/api/googleapis/transport.APIKey, use option.WithAPIKey with NewService instead. +func New(client *http.Client) (*Service, error) { + if client == nil { + return nil, errors.New("client is nil") + } + s := &Service{client: client, BasePath: basePath} + s.Asps = NewAspsService(s) + s.Channels = NewChannelsService(s) + s.Chromeosdevices = NewChromeosdevicesService(s) + s.Customers = NewCustomersService(s) + s.DomainAliases = NewDomainAliasesService(s) + s.Domains = NewDomainsService(s) + s.Groups = NewGroupsService(s) + s.Members = NewMembersService(s) + s.Mobiledevices = NewMobiledevicesService(s) + s.Notifications = NewNotificationsService(s) + s.Orgunits = NewOrgunitsService(s) + s.Privileges = NewPrivilegesService(s) + s.ResolvedAppAccessSettings = NewResolvedAppAccessSettingsService(s) + s.Resources = NewResourcesService(s) + s.RoleAssignments = NewRoleAssignmentsService(s) + s.Roles = NewRolesService(s) + s.Schemas = NewSchemasService(s) + s.Tokens = NewTokensService(s) + s.Users = NewUsersService(s) + s.VerificationCodes = NewVerificationCodesService(s) + return s, nil +} + +type Service struct { + client *http.Client + BasePath string // API endpoint base URL + UserAgent string // optional additional User-Agent fragment + + Asps *AspsService + + Channels *ChannelsService + + Chromeosdevices *ChromeosdevicesService + + Customers *CustomersService + + DomainAliases *DomainAliasesService + + Domains *DomainsService + + Groups *GroupsService + + Members *MembersService + + Mobiledevices *MobiledevicesService + + Notifications *NotificationsService + + Orgunits *OrgunitsService + + Privileges *PrivilegesService + + ResolvedAppAccessSettings *ResolvedAppAccessSettingsService + + Resources *ResourcesService + + RoleAssignments *RoleAssignmentsService + + Roles *RolesService + + Schemas *SchemasService + + Tokens *TokensService + + Users *UsersService + + VerificationCodes *VerificationCodesService +} + +func (s *Service) userAgent() string { + if s.UserAgent == "" { + return googleapi.UserAgent + } + return googleapi.UserAgent + " " + s.UserAgent +} + +func NewAspsService(s *Service) *AspsService { + rs := &AspsService{s: s} + return rs +} + +type AspsService struct { + s *Service +} + +func NewChannelsService(s *Service) *ChannelsService { + rs := &ChannelsService{s: s} + return rs +} + +type ChannelsService struct { + s *Service +} + +func NewChromeosdevicesService(s *Service) *ChromeosdevicesService { + rs := &ChromeosdevicesService{s: s} + return rs +} + +type ChromeosdevicesService struct { + s *Service +} + +func NewCustomersService(s *Service) *CustomersService { + rs := &CustomersService{s: s} + return rs +} + +type CustomersService struct { + s *Service +} + +func NewDomainAliasesService(s *Service) *DomainAliasesService { + rs := &DomainAliasesService{s: s} + return rs +} + +type DomainAliasesService struct { + s *Service +} + +func NewDomainsService(s *Service) *DomainsService { + rs := &DomainsService{s: s} + return rs +} + +type DomainsService struct { + s *Service +} + +func NewGroupsService(s *Service) *GroupsService { + rs := &GroupsService{s: s} + rs.Aliases = NewGroupsAliasesService(s) + return rs +} + +type GroupsService struct { + s *Service + + Aliases *GroupsAliasesService +} + +func NewGroupsAliasesService(s *Service) *GroupsAliasesService { + rs := &GroupsAliasesService{s: s} + return rs +} + +type GroupsAliasesService struct { + s *Service +} + +func NewMembersService(s *Service) *MembersService { + rs := &MembersService{s: s} + return rs +} + +type MembersService struct { + s *Service +} + +func NewMobiledevicesService(s *Service) *MobiledevicesService { + rs := &MobiledevicesService{s: s} + return rs +} + +type MobiledevicesService struct { + s *Service +} + +func NewNotificationsService(s *Service) *NotificationsService { + rs := &NotificationsService{s: s} + return rs +} + +type NotificationsService struct { + s *Service +} + +func NewOrgunitsService(s *Service) *OrgunitsService { + rs := &OrgunitsService{s: s} + return rs +} + +type OrgunitsService struct { + s *Service +} + +func NewPrivilegesService(s *Service) *PrivilegesService { + rs := &PrivilegesService{s: s} + return rs +} + +type PrivilegesService struct { + s *Service +} + +func NewResolvedAppAccessSettingsService(s *Service) *ResolvedAppAccessSettingsService { + rs := &ResolvedAppAccessSettingsService{s: s} + return rs +} + +type ResolvedAppAccessSettingsService struct { + s *Service +} + +func NewResourcesService(s *Service) *ResourcesService { + rs := &ResourcesService{s: s} + rs.Buildings = NewResourcesBuildingsService(s) + rs.Calendars = NewResourcesCalendarsService(s) + rs.Features = NewResourcesFeaturesService(s) + return rs +} + +type ResourcesService struct { + s *Service + + Buildings *ResourcesBuildingsService + + Calendars *ResourcesCalendarsService + + Features *ResourcesFeaturesService +} + +func NewResourcesBuildingsService(s *Service) *ResourcesBuildingsService { + rs := &ResourcesBuildingsService{s: s} + return rs +} + +type ResourcesBuildingsService struct { + s *Service +} + +func NewResourcesCalendarsService(s *Service) *ResourcesCalendarsService { + rs := &ResourcesCalendarsService{s: s} + return rs +} + +type ResourcesCalendarsService struct { + s *Service +} + +func NewResourcesFeaturesService(s *Service) *ResourcesFeaturesService { + rs := &ResourcesFeaturesService{s: s} + return rs +} + +type ResourcesFeaturesService struct { + s *Service +} + +func NewRoleAssignmentsService(s *Service) *RoleAssignmentsService { + rs := &RoleAssignmentsService{s: s} + return rs +} + +type RoleAssignmentsService struct { + s *Service +} + +func NewRolesService(s *Service) *RolesService { + rs := &RolesService{s: s} + return rs +} + +type RolesService struct { + s *Service +} + +func NewSchemasService(s *Service) *SchemasService { + rs := &SchemasService{s: s} + return rs +} + +type SchemasService struct { + s *Service +} + +func NewTokensService(s *Service) *TokensService { + rs := &TokensService{s: s} + return rs +} + +type TokensService struct { + s *Service +} + +func NewUsersService(s *Service) *UsersService { + rs := &UsersService{s: s} + rs.Aliases = NewUsersAliasesService(s) + rs.Photos = NewUsersPhotosService(s) + return rs +} + +type UsersService struct { + s *Service + + Aliases *UsersAliasesService + + Photos *UsersPhotosService +} + +func NewUsersAliasesService(s *Service) *UsersAliasesService { + rs := &UsersAliasesService{s: s} + return rs +} + +type UsersAliasesService struct { + s *Service +} + +func NewUsersPhotosService(s *Service) *UsersPhotosService { + rs := &UsersPhotosService{s: s} + return rs +} + +type UsersPhotosService struct { + s *Service +} + +func NewVerificationCodesService(s *Service) *VerificationCodesService { + rs := &VerificationCodesService{s: s} + return rs +} + +type VerificationCodesService struct { + s *Service +} + +// Alias: JSON template for Alias object in Directory API. +type Alias struct { + // Alias: A alias email + Alias string `json:"alias,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Id: Unique id of the group (Read-only) Unique id of the user + // (Read-only) + Id string `json:"id,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // PrimaryEmail: Group's primary email (Read-only) User's primary email + // (Read-only) + PrimaryEmail string `json:"primaryEmail,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Alias") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Alias") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Alias) MarshalJSON() ([]byte, error) { + type NoMethod Alias + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Aliases: JSON response template to list aliases in Directory API. +type Aliases struct { + // Aliases: List of alias objects. + Aliases []interface{} `json:"aliases,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Aliases") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Aliases") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Aliases) MarshalJSON() ([]byte, error) { + type NoMethod Aliases + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// AppAccessCollections: JSON template for App Access Collections +// Resource object in Directory API. +type AppAccessCollections struct { + // BlockedApiAccessBuckets: List of blocked api access buckets. + BlockedApiAccessBuckets []string `json:"blockedApiAccessBuckets,omitempty"` + + // EnforceSettingsForAndroidDrive: Boolean to indicate whether to + // enforce app access settings on Android Drive or not. + EnforceSettingsForAndroidDrive bool `json:"enforceSettingsForAndroidDrive,omitempty"` + + // ErrorMessage: Error message provided by the Admin that will be shown + // to the user when an app is blocked. + ErrorMessage string `json:"errorMessage,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Identifies the resource as an app access collection. Value: + // admin#directory#appaccesscollection + Kind string `json:"kind,omitempty"` + + // ResourceId: Unique ID of app access collection. (Readonly) + ResourceId int64 `json:"resourceId,omitempty,string"` + + // ResourceName: Resource name given by the customer while + // creating/updating. Should be unique under given customer. + ResourceName string `json:"resourceName,omitempty"` + + // TrustDomainOwnedApps: Boolean that indicates whether to trust domain + // owned apps. + TrustDomainOwnedApps bool `json:"trustDomainOwnedApps,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. + // "BlockedApiAccessBuckets") to unconditionally include in API + // requests. By default, fields with empty values are omitted from API + // requests. However, any non-pointer, non-interface field appearing in + // ForceSendFields will be sent to the server regardless of whether the + // field is empty or not. This may be used to include empty fields in + // Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "BlockedApiAccessBuckets") + // to include in API requests with the JSON null value. By default, + // fields with empty values are omitted from API requests. However, any + // field with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *AppAccessCollections) MarshalJSON() ([]byte, error) { + type NoMethod AppAccessCollections + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Asp: The template that returns individual ASP (Access Code) data. +type Asp struct { + // CodeId: The unique ID of the ASP. + CodeId int64 `json:"codeId,omitempty"` + + // CreationTime: The time when the ASP was created. Expressed in Unix + // time format. + CreationTime int64 `json:"creationTime,omitempty,string"` + + // Etag: ETag of the ASP. + Etag string `json:"etag,omitempty"` + + // Kind: The type of the API resource. This is always + // admin#directory#asp. + Kind string `json:"kind,omitempty"` + + // LastTimeUsed: The time when the ASP was last used. Expressed in Unix + // time format. + LastTimeUsed int64 `json:"lastTimeUsed,omitempty,string"` + + // Name: The name of the application that the user, represented by their + // userId, entered when the ASP was created. + Name string `json:"name,omitempty"` + + // UserKey: The unique ID of the user who issued the ASP. + UserKey string `json:"userKey,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "CodeId") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CodeId") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Asp) MarshalJSON() ([]byte, error) { + type NoMethod Asp + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type Asps struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Items: A list of ASP resources. + Items []*Asp `json:"items,omitempty"` + + // Kind: The type of the API resource. This is always + // admin#directory#aspList. + Kind string `json:"kind,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Asps) MarshalJSON() ([]byte, error) { + type NoMethod Asps + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Building: JSON template for Building object in Directory API. +type Building struct { + // Address: The postal address of the building. See PostalAddress for + // details. Note that only a single address line and region code are + // required. + Address *BuildingAddress `json:"address,omitempty"` + + // BuildingId: Unique identifier for the building. The maximum length is + // 100 characters. + BuildingId string `json:"buildingId,omitempty"` + + // BuildingName: The building name as seen by users in Calendar. Must be + // unique for the customer. For example, "NYC-CHEL". The maximum length + // is 100 characters. + BuildingName string `json:"buildingName,omitempty"` + + // Coordinates: The geographic coordinates of the center of the + // building, expressed as latitude and longitude in decimal degrees. + Coordinates *BuildingCoordinates `json:"coordinates,omitempty"` + + // Description: A brief description of the building. For example, + // "Chelsea Market". + Description string `json:"description,omitempty"` + + // Etags: ETag of the resource. + Etags string `json:"etags,omitempty"` + + // FloorNames: The display names for all floors in this building. The + // floors are expected to be sorted in ascending order, from lowest + // floor to highest floor. For example, ["B2", "B1", "L", "1", "2", + // "2M", "3", "PH"] Must contain at least one entry. + FloorNames []string `json:"floorNames,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Address") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Address") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Building) MarshalJSON() ([]byte, error) { + type NoMethod Building + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// BuildingAddress: JSON template for the postal address of a building +// in Directory API. +type BuildingAddress struct { + // AddressLines: Unstructured address lines describing the lower levels + // of an address. + AddressLines []string `json:"addressLines,omitempty"` + + // AdministrativeArea: Optional. Highest administrative subdivision + // which is used for postal addresses of a country or region. + AdministrativeArea string `json:"administrativeArea,omitempty"` + + // LanguageCode: Optional. BCP-47 language code of the contents of this + // address (if known). + LanguageCode string `json:"languageCode,omitempty"` + + // Locality: Optional. Generally refers to the city/town portion of the + // address. Examples: US city, IT comune, UK post town. In regions of + // the world where localities are not well defined or do not fit into + // this structure well, leave locality empty and use addressLines. + Locality string `json:"locality,omitempty"` + + // PostalCode: Optional. Postal code of the address. + PostalCode string `json:"postalCode,omitempty"` + + // RegionCode: Required. CLDR region code of the country/region of the + // address. + RegionCode string `json:"regionCode,omitempty"` + + // Sublocality: Optional. Sublocality of the address. + Sublocality string `json:"sublocality,omitempty"` + + // ForceSendFields is a list of field names (e.g. "AddressLines") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "AddressLines") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *BuildingAddress) MarshalJSON() ([]byte, error) { + type NoMethod BuildingAddress + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// BuildingCoordinates: JSON template for coordinates of a building in +// Directory API. +type BuildingCoordinates struct { + // Latitude: Latitude in decimal degrees. + Latitude float64 `json:"latitude,omitempty"` + + // Longitude: Longitude in decimal degrees. + Longitude float64 `json:"longitude,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Latitude") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Latitude") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *BuildingCoordinates) MarshalJSON() ([]byte, error) { + type NoMethod BuildingCoordinates + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +func (s *BuildingCoordinates) UnmarshalJSON(data []byte) error { + type NoMethod BuildingCoordinates + var s1 struct { + Latitude gensupport.JSONFloat64 `json:"latitude"` + Longitude gensupport.JSONFloat64 `json:"longitude"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.Latitude = float64(s1.Latitude) + s.Longitude = float64(s1.Longitude) + return nil +} + +// Buildings: JSON template for Building List Response object in +// Directory API. +type Buildings struct { + // Buildings: The Buildings in this page of results. + Buildings []*Building `json:"buildings,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // NextPageToken: The continuation token, used to page through large + // result sets. Provide this value in a subsequent request to return the + // next page of results. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Buildings") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Buildings") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Buildings) MarshalJSON() ([]byte, error) { + type NoMethod Buildings + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// CalendarResource: JSON template for Calendar Resource object in +// Directory API. +type CalendarResource struct { + // BuildingId: Unique ID for the building a resource is located in. + BuildingId string `json:"buildingId,omitempty"` + + // Capacity: Capacity of a resource, number of seats in a room. + Capacity int64 `json:"capacity,omitempty"` + + // Etags: ETag of the resource. + Etags string `json:"etags,omitempty"` + + FeatureInstances interface{} `json:"featureInstances,omitempty"` + + // FloorName: Name of the floor a resource is located on. + FloorName string `json:"floorName,omitempty"` + + // FloorSection: Name of the section within a floor a resource is + // located in. + FloorSection string `json:"floorSection,omitempty"` + + // GeneratedResourceName: The read-only auto-generated name of the + // calendar resource which includes metadata about the resource such as + // building name, floor, capacity, etc. For example, "NYC-2-Training + // Room 1A (16)". + GeneratedResourceName string `json:"generatedResourceName,omitempty"` + + // Kind: The type of the resource. For calendar resources, the value is + // admin#directory#resources#calendars#CalendarResource. + Kind string `json:"kind,omitempty"` + + // ResourceCategory: The category of the calendar resource. Either + // CONFERENCE_ROOM or OTHER. Legacy data is set to CATEGORY_UNKNOWN. + ResourceCategory string `json:"resourceCategory,omitempty"` + + // ResourceDescription: Description of the resource, visible only to + // admins. + ResourceDescription string `json:"resourceDescription,omitempty"` + + // ResourceEmail: The read-only email for the calendar resource. + // Generated as part of creating a new calendar resource. + ResourceEmail string `json:"resourceEmail,omitempty"` + + // ResourceId: The unique ID for the calendar resource. + ResourceId string `json:"resourceId,omitempty"` + + // ResourceName: The name of the calendar resource. For example, + // "Training Room 1A". + ResourceName string `json:"resourceName,omitempty"` + + // ResourceType: The type of the calendar resource, intended for + // non-room resources. + ResourceType string `json:"resourceType,omitempty"` + + // UserVisibleDescription: Description of the resource, visible to users + // and admins. + UserVisibleDescription string `json:"userVisibleDescription,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "BuildingId") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "BuildingId") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *CalendarResource) MarshalJSON() ([]byte, error) { + type NoMethod CalendarResource + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// CalendarResources: JSON template for Calendar Resource List Response +// object in Directory API. +type CalendarResources struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Items: The CalendarResources in this page of results. + Items []*CalendarResource `json:"items,omitempty"` + + // Kind: Identifies this as a collection of CalendarResources. This is + // always admin#directory#resources#calendars#calendarResourcesList. + Kind string `json:"kind,omitempty"` + + // NextPageToken: The continuation token, used to page through large + // result sets. Provide this value in a subsequent request to return the + // next page of results. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *CalendarResources) MarshalJSON() ([]byte, error) { + type NoMethod CalendarResources + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Channel: An notification channel used to watch for resource changes. +type Channel struct { + // Address: The address where notifications are delivered for this + // channel. + Address string `json:"address,omitempty"` + + // Expiration: Date and time of notification channel expiration, + // expressed as a Unix timestamp, in milliseconds. Optional. + Expiration int64 `json:"expiration,omitempty,string"` + + // Id: A UUID or similar unique string that identifies this channel. + Id string `json:"id,omitempty"` + + // Kind: Identifies this as a notification channel used to watch for + // changes to a resource, which is "api#channel". + Kind string `json:"kind,omitempty"` + + // Params: Additional parameters controlling delivery channel behavior. + // Optional. + Params map[string]string `json:"params,omitempty"` + + // Payload: A Boolean value to indicate whether payload is wanted. + // Optional. + Payload bool `json:"payload,omitempty"` + + // ResourceId: An opaque ID that identifies the resource being watched + // on this channel. Stable across different API versions. + ResourceId string `json:"resourceId,omitempty"` + + // ResourceUri: A version-specific identifier for the watched resource. + ResourceUri string `json:"resourceUri,omitempty"` + + // Token: An arbitrary string delivered to the target address with each + // notification delivered over this channel. Optional. + Token string `json:"token,omitempty"` + + // Type: The type of delivery mechanism used for this channel. + Type string `json:"type,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Address") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Address") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Channel) MarshalJSON() ([]byte, error) { + type NoMethod Channel + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// ChromeOsDevice: JSON template for Chrome Os Device resource in +// Directory API. +type ChromeOsDevice struct { + // ActiveTimeRanges: List of active time ranges (Read-only) + ActiveTimeRanges []*ChromeOsDeviceActiveTimeRanges `json:"activeTimeRanges,omitempty"` + + // AnnotatedAssetId: AssetId specified during enrollment or through + // later annotation + AnnotatedAssetId string `json:"annotatedAssetId,omitempty"` + + // AnnotatedLocation: Address or location of the device as noted by the + // administrator + AnnotatedLocation string `json:"annotatedLocation,omitempty"` + + // AnnotatedUser: User of the device + AnnotatedUser string `json:"annotatedUser,omitempty"` + + // AutoUpdateExpiration: (Read-only) The timestamp after which the + // device will stop receiving Chrome updates or support + AutoUpdateExpiration int64 `json:"autoUpdateExpiration,omitempty,string"` + + // BootMode: Chromebook boot mode (Read-only) + BootMode string `json:"bootMode,omitempty"` + + // CpuStatusReports: Reports of CPU utilization and temperature + // (Read-only) + CpuStatusReports []*ChromeOsDeviceCpuStatusReports `json:"cpuStatusReports,omitempty"` + + // DeviceFiles: List of device files to download (Read-only) + DeviceFiles []*ChromeOsDeviceDeviceFiles `json:"deviceFiles,omitempty"` + + // DeviceId: Unique identifier of Chrome OS Device (Read-only) + DeviceId string `json:"deviceId,omitempty"` + + // DiskVolumeReports: Reports of disk space and other info about + // mounted/connected volumes. + DiskVolumeReports []*ChromeOsDeviceDiskVolumeReports `json:"diskVolumeReports,omitempty"` + + // DockMacAddress: (Read-only) Built-in MAC address for the docking + // station that the device connected to. Factory sets Media access + // control address (MAC address) assigned for use by a dock. Currently + // this is only supported on the Dell Arcada / Sarien devices and the + // Dell WD19 / WD19TB Docking Station. It is reserved specifically for + // MAC pass through device policy. The format is twelve (12) hexadecimal + // digits without any delimiter (uppercase letters). This is only + // relevant for Dell devices. + DockMacAddress string `json:"dockMacAddress,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // EthernetMacAddress: Chromebook Mac Address on ethernet network + // interface (Read-only) + EthernetMacAddress string `json:"ethernetMacAddress,omitempty"` + + // EthernetMacAddress0: (Read-only) MAC address used by the + // Chromebook’s internal ethernet port, and for onboard network + // (ethernet) interface. The format is twelve (12) hexadecimal digits + // without any delimiter (uppercase letters). This is only relevant for + // Dell devices. + EthernetMacAddress0 string `json:"ethernetMacAddress0,omitempty"` + + // FirmwareVersion: Chromebook firmware version (Read-only) + FirmwareVersion string `json:"firmwareVersion,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // LastEnrollmentTime: Date and time the device was last enrolled + // (Read-only) + LastEnrollmentTime string `json:"lastEnrollmentTime,omitempty"` + + // LastSync: Date and time the device was last synchronized with the + // policy settings in the G Suite administrator control panel + // (Read-only) + LastSync string `json:"lastSync,omitempty"` + + // MacAddress: Chromebook Mac Address on wifi network interface + // (Read-only) + MacAddress string `json:"macAddress,omitempty"` + + // ManufactureDate: (Read-only) The date the device was manufactured in + // yyyy-mm-dd format. + ManufactureDate string `json:"manufactureDate,omitempty"` + + // Meid: Mobile Equipment identifier for the 3G mobile card in the + // Chromebook (Read-only) + Meid string `json:"meid,omitempty"` + + // Model: Chromebook Model (Read-only) + Model string `json:"model,omitempty"` + + // Notes: Notes added by the administrator + Notes string `json:"notes,omitempty"` + + // OrderNumber: Chromebook order number (Read-only) + OrderNumber string `json:"orderNumber,omitempty"` + + // OrgUnitPath: OrgUnit of the device + OrgUnitPath string `json:"orgUnitPath,omitempty"` + + // OsVersion: Chromebook Os Version (Read-only) + OsVersion string `json:"osVersion,omitempty"` + + // PlatformVersion: Chromebook platform version (Read-only) + PlatformVersion string `json:"platformVersion,omitempty"` + + // RecentUsers: List of recent device users, in descending order by last + // login time (Read-only) + RecentUsers []*ChromeOsDeviceRecentUsers `json:"recentUsers,omitempty"` + + // SerialNumber: Chromebook serial number (Read-only) + SerialNumber string `json:"serialNumber,omitempty"` + + // Status: status of the device (Read-only) + Status string `json:"status,omitempty"` + + // SupportEndDate: Final date the device will be supported (Read-only) + SupportEndDate string `json:"supportEndDate,omitempty"` + + // SystemRamFreeReports: Reports of amounts of available RAM memory + // (Read-only) + SystemRamFreeReports []*ChromeOsDeviceSystemRamFreeReports `json:"systemRamFreeReports,omitempty"` + + // SystemRamTotal: Total RAM on the device [in bytes] (Read-only) + SystemRamTotal int64 `json:"systemRamTotal,omitempty,string"` + + // TpmVersionInfo: Trusted Platform Module (TPM) (Read-only) + TpmVersionInfo *ChromeOsDeviceTpmVersionInfo `json:"tpmVersionInfo,omitempty"` + + // WillAutoRenew: Will Chromebook auto renew after support end date + // (Read-only) + WillAutoRenew bool `json:"willAutoRenew,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "ActiveTimeRanges") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "ActiveTimeRanges") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *ChromeOsDevice) MarshalJSON() ([]byte, error) { + type NoMethod ChromeOsDevice + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ChromeOsDeviceActiveTimeRanges struct { + // ActiveTime: Duration in milliseconds + ActiveTime int64 `json:"activeTime,omitempty"` + + // Date: Date of usage + Date string `json:"date,omitempty"` + + // ForceSendFields is a list of field names (e.g. "ActiveTime") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "ActiveTime") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ChromeOsDeviceActiveTimeRanges) MarshalJSON() ([]byte, error) { + type NoMethod ChromeOsDeviceActiveTimeRanges + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ChromeOsDeviceCpuStatusReports struct { + // CpuTemperatureInfo: List of CPU temperature samples. + CpuTemperatureInfo []*ChromeOsDeviceCpuStatusReportsCpuTemperatureInfo `json:"cpuTemperatureInfo,omitempty"` + + CpuUtilizationPercentageInfo []int64 `json:"cpuUtilizationPercentageInfo,omitempty"` + + // ReportTime: Date and time the report was received. + ReportTime string `json:"reportTime,omitempty"` + + // ForceSendFields is a list of field names (e.g. "CpuTemperatureInfo") + // to unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CpuTemperatureInfo") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *ChromeOsDeviceCpuStatusReports) MarshalJSON() ([]byte, error) { + type NoMethod ChromeOsDeviceCpuStatusReports + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ChromeOsDeviceCpuStatusReportsCpuTemperatureInfo struct { + // Label: CPU label + Label string `json:"label,omitempty"` + + // Temperature: Temperature in Celsius degrees. + Temperature int64 `json:"temperature,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Label") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Label") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ChromeOsDeviceCpuStatusReportsCpuTemperatureInfo) MarshalJSON() ([]byte, error) { + type NoMethod ChromeOsDeviceCpuStatusReportsCpuTemperatureInfo + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ChromeOsDeviceDeviceFiles struct { + // CreateTime: Date and time the file was created + CreateTime string `json:"createTime,omitempty"` + + // DownloadUrl: File download URL + DownloadUrl string `json:"downloadUrl,omitempty"` + + // Name: File name + Name string `json:"name,omitempty"` + + // Type: File type + Type string `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "CreateTime") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CreateTime") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ChromeOsDeviceDeviceFiles) MarshalJSON() ([]byte, error) { + type NoMethod ChromeOsDeviceDeviceFiles + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ChromeOsDeviceDiskVolumeReports struct { + // VolumeInfo: Disk volumes + VolumeInfo []*ChromeOsDeviceDiskVolumeReportsVolumeInfo `json:"volumeInfo,omitempty"` + + // ForceSendFields is a list of field names (e.g. "VolumeInfo") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "VolumeInfo") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ChromeOsDeviceDiskVolumeReports) MarshalJSON() ([]byte, error) { + type NoMethod ChromeOsDeviceDiskVolumeReports + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ChromeOsDeviceDiskVolumeReportsVolumeInfo struct { + // StorageFree: Free disk space [in bytes] + StorageFree int64 `json:"storageFree,omitempty,string"` + + // StorageTotal: Total disk space [in bytes] + StorageTotal int64 `json:"storageTotal,omitempty,string"` + + // VolumeId: Volume id + VolumeId string `json:"volumeId,omitempty"` + + // ForceSendFields is a list of field names (e.g. "StorageFree") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "StorageFree") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ChromeOsDeviceDiskVolumeReportsVolumeInfo) MarshalJSON() ([]byte, error) { + type NoMethod ChromeOsDeviceDiskVolumeReportsVolumeInfo + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ChromeOsDeviceRecentUsers struct { + // Email: Email address of the user. Present only if the user type is + // managed + Email string `json:"email,omitempty"` + + // Type: The type of the user + Type string `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Email") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Email") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ChromeOsDeviceRecentUsers) MarshalJSON() ([]byte, error) { + type NoMethod ChromeOsDeviceRecentUsers + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ChromeOsDeviceSystemRamFreeReports struct { + // ReportTime: Date and time the report was received. + ReportTime string `json:"reportTime,omitempty"` + + SystemRamFreeInfo googleapi.Int64s `json:"systemRamFreeInfo,omitempty"` + + // ForceSendFields is a list of field names (e.g. "ReportTime") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "ReportTime") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ChromeOsDeviceSystemRamFreeReports) MarshalJSON() ([]byte, error) { + type NoMethod ChromeOsDeviceSystemRamFreeReports + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// ChromeOsDeviceTpmVersionInfo: Trusted Platform Module (TPM) +// (Read-only) +type ChromeOsDeviceTpmVersionInfo struct { + // Family: TPM family. + Family string `json:"family,omitempty"` + + // FirmwareVersion: TPM firmware version. + FirmwareVersion string `json:"firmwareVersion,omitempty"` + + // Manufacturer: TPM manufacturer code. + Manufacturer string `json:"manufacturer,omitempty"` + + // SpecLevel: TPM specification level. + SpecLevel string `json:"specLevel,omitempty"` + + // TpmModel: TPM model number. + TpmModel string `json:"tpmModel,omitempty"` + + // VendorSpecific: Vendor-specific information such as Vendor ID. + VendorSpecific string `json:"vendorSpecific,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Family") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Family") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ChromeOsDeviceTpmVersionInfo) MarshalJSON() ([]byte, error) { + type NoMethod ChromeOsDeviceTpmVersionInfo + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// ChromeOsDeviceAction: JSON request template for firing actions on +// ChromeOs Device in Directory Devices API. +type ChromeOsDeviceAction struct { + // Action: Action to be taken on the ChromeOs Device + Action string `json:"action,omitempty"` + + DeprovisionReason string `json:"deprovisionReason,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Action") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Action") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ChromeOsDeviceAction) MarshalJSON() ([]byte, error) { + type NoMethod ChromeOsDeviceAction + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// ChromeOsDevices: JSON response template for List Chrome OS Devices +// operation in Directory API. +type ChromeOsDevices struct { + // Chromeosdevices: List of Chrome OS Device objects. + Chromeosdevices []*ChromeOsDevice `json:"chromeosdevices,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // NextPageToken: Token used to access next page of this result. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Chromeosdevices") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Chromeosdevices") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *ChromeOsDevices) MarshalJSON() ([]byte, error) { + type NoMethod ChromeOsDevices + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// ChromeOsMoveDevicesToOu: JSON request template for moving ChromeOs +// Device to given OU in Directory Devices API. +type ChromeOsMoveDevicesToOu struct { + // DeviceIds: ChromeOs Devices to be moved to OU + DeviceIds []string `json:"deviceIds,omitempty"` + + // ForceSendFields is a list of field names (e.g. "DeviceIds") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "DeviceIds") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ChromeOsMoveDevicesToOu) MarshalJSON() ([]byte, error) { + type NoMethod ChromeOsMoveDevicesToOu + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Customer: JSON template for Customer Resource object in Directory +// API. +type Customer struct { + // AlternateEmail: The customer's secondary contact email address. This + // email address cannot be on the same domain as the customerDomain + AlternateEmail string `json:"alternateEmail,omitempty"` + + // CustomerCreationTime: The customer's creation time (Readonly) + CustomerCreationTime string `json:"customerCreationTime,omitempty"` + + // CustomerDomain: The customer's primary domain name string. Do not + // include the www prefix when creating a new customer. + CustomerDomain string `json:"customerDomain,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Id: The unique ID for the customer's G Suite account. (Readonly) + Id string `json:"id,omitempty"` + + // Kind: Identifies the resource as a customer. Value: + // admin#directory#customer + Kind string `json:"kind,omitempty"` + + // Language: The customer's ISO 639-2 language code. The default value + // is en-US + Language string `json:"language,omitempty"` + + // PhoneNumber: The customer's contact phone number in E.164 format. + PhoneNumber string `json:"phoneNumber,omitempty"` + + // PostalAddress: The customer's postal address information. + PostalAddress *CustomerPostalAddress `json:"postalAddress,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "AlternateEmail") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "AlternateEmail") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *Customer) MarshalJSON() ([]byte, error) { + type NoMethod Customer + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// CustomerPostalAddress: JSON template for postal address of a +// customer. +type CustomerPostalAddress struct { + // AddressLine1: A customer's physical address. The address can be + // composed of one to three lines. + AddressLine1 string `json:"addressLine1,omitempty"` + + // AddressLine2: Address line 2 of the address. + AddressLine2 string `json:"addressLine2,omitempty"` + + // AddressLine3: Address line 3 of the address. + AddressLine3 string `json:"addressLine3,omitempty"` + + // ContactName: The customer contact's name. + ContactName string `json:"contactName,omitempty"` + + // CountryCode: This is a required property. For countryCode information + // see the ISO 3166 country code elements. + CountryCode string `json:"countryCode,omitempty"` + + // Locality: Name of the locality. An example of a locality value is the + // city of San Francisco. + Locality string `json:"locality,omitempty"` + + // OrganizationName: The company or company division name. + OrganizationName string `json:"organizationName,omitempty"` + + // PostalCode: The postal code. A postalCode example is a postal zip + // code such as 10009. This is in accordance with - + // http://portablecontacts.net/draft-spec.html#address_element. + PostalCode string `json:"postalCode,omitempty"` + + // Region: Name of the region. An example of a region value is NY for + // the state of New York. + Region string `json:"region,omitempty"` + + // ForceSendFields is a list of field names (e.g. "AddressLine1") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "AddressLine1") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *CustomerPostalAddress) MarshalJSON() ([]byte, error) { + type NoMethod CustomerPostalAddress + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// DomainAlias: JSON template for Domain Alias object in Directory API. +type DomainAlias struct { + // CreationTime: The creation time of the domain alias. (Read-only). + CreationTime int64 `json:"creationTime,omitempty,string"` + + // DomainAliasName: The domain alias name. + DomainAliasName string `json:"domainAliasName,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // ParentDomainName: The parent domain name that the domain alias is + // associated with. This can either be a primary or secondary domain + // name within a customer. + ParentDomainName string `json:"parentDomainName,omitempty"` + + // Verified: Indicates the verification state of a domain alias. + // (Read-only) + Verified bool `json:"verified,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "CreationTime") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CreationTime") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *DomainAlias) MarshalJSON() ([]byte, error) { + type NoMethod DomainAlias + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// DomainAliases: JSON response template to list domain aliases in +// Directory API. +type DomainAliases struct { + // DomainAliases: List of domain alias objects. + DomainAliases []*DomainAlias `json:"domainAliases,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "DomainAliases") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "DomainAliases") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *DomainAliases) MarshalJSON() ([]byte, error) { + type NoMethod DomainAliases + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Domains: JSON template for Domain object in Directory API. +type Domains struct { + // CreationTime: Creation time of the domain. (Read-only). + CreationTime int64 `json:"creationTime,omitempty,string"` + + // DomainAliases: List of domain alias objects. (Read-only) + DomainAliases []*DomainAlias `json:"domainAliases,omitempty"` + + // DomainName: The domain name of the customer. + DomainName string `json:"domainName,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // IsPrimary: Indicates if the domain is a primary domain (Read-only). + IsPrimary bool `json:"isPrimary,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // Verified: Indicates the verification state of a domain. (Read-only). + Verified bool `json:"verified,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "CreationTime") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CreationTime") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Domains) MarshalJSON() ([]byte, error) { + type NoMethod Domains + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Domains2: JSON response template to list Domains in Directory API. +type Domains2 struct { + // Domains: List of domain objects. + Domains []*Domains `json:"domains,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Domains") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Domains") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Domains2) MarshalJSON() ([]byte, error) { + type NoMethod Domains2 + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Feature: JSON template for Feature object in Directory API. +type Feature struct { + // Etags: ETag of the resource. + Etags string `json:"etags,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // Name: The name of the feature. + Name string `json:"name,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etags") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etags") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Feature) MarshalJSON() ([]byte, error) { + type NoMethod Feature + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// FeatureInstance: JSON template for a "feature instance". +type FeatureInstance struct { + // Feature: The feature that this is an instance of. A calendar resource + // may have multiple instances of a feature. + Feature *Feature `json:"feature,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Feature") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Feature") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *FeatureInstance) MarshalJSON() ([]byte, error) { + type NoMethod FeatureInstance + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// FeatureRename: JSON request template for renaming a feature. +type FeatureRename struct { + // NewName: New name of the feature. + NewName string `json:"newName,omitempty"` + + // ForceSendFields is a list of field names (e.g. "NewName") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "NewName") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *FeatureRename) MarshalJSON() ([]byte, error) { + type NoMethod FeatureRename + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Features: JSON template for Feature List Response object in Directory +// API. +type Features struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Features: The Features in this page of results. + Features []*Feature `json:"features,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // NextPageToken: The continuation token, used to page through large + // result sets. Provide this value in a subsequent request to return the + // next page of results. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Features) MarshalJSON() ([]byte, error) { + type NoMethod Features + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Group: JSON template for Group resource in Directory API. +type Group struct { + // AdminCreated: Is the group created by admin (Read-only) * + AdminCreated bool `json:"adminCreated,omitempty"` + + // Aliases: List of aliases (Read-only) + Aliases []string `json:"aliases,omitempty"` + + // Description: Description of the group + Description string `json:"description,omitempty"` + + // DirectMembersCount: Group direct members count + DirectMembersCount int64 `json:"directMembersCount,omitempty,string"` + + // Email: Email of Group + Email string `json:"email,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Id: Unique identifier of Group (Read-only) + Id string `json:"id,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // Name: Group name + Name string `json:"name,omitempty"` + + // NonEditableAliases: List of non editable aliases (Read-only) + NonEditableAliases []string `json:"nonEditableAliases,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "AdminCreated") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "AdminCreated") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Group) MarshalJSON() ([]byte, error) { + type NoMethod Group + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Groups: JSON response template for List Groups operation in Directory +// API. +type Groups struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Groups: List of group objects. + Groups []*Group `json:"groups,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // NextPageToken: Token used to access next page of this result. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Groups) MarshalJSON() ([]byte, error) { + type NoMethod Groups + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Member: JSON template for Member resource in Directory API. +type Member struct { + // DeliverySettings: Delivery settings of member + DeliverySettings string `json:"delivery_settings,omitempty"` + + // Email: Email of member (Read-only) + Email string `json:"email,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Id: The unique ID of the group member. A member id can be used as a + // member request URI's memberKey. Unique identifier of group + // (Read-only) Unique identifier of member (Read-only) + Id string `json:"id,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // Role: Role of member + Role string `json:"role,omitempty"` + + // Status: Status of member (Immutable) + Status string `json:"status,omitempty"` + + // Type: Type of member (Immutable) + Type string `json:"type,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "DeliverySettings") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "DeliverySettings") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *Member) MarshalJSON() ([]byte, error) { + type NoMethod Member + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Members: JSON response template for List Members operation in +// Directory API. +type Members struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // Members: List of member objects. + Members []*Member `json:"members,omitempty"` + + // NextPageToken: Token used to access next page of this result. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Members) MarshalJSON() ([]byte, error) { + type NoMethod Members + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// MembersHasMember: JSON template for Has Member response in Directory +// API. +type MembersHasMember struct { + // IsMember: Identifies whether the given user is a member of the group. + // Membership can be direct or nested. + IsMember bool `json:"isMember,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "IsMember") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "IsMember") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *MembersHasMember) MarshalJSON() ([]byte, error) { + type NoMethod MembersHasMember + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// MobileDevice: JSON template for Mobile Device resource in Directory +// API. +type MobileDevice struct { + // AdbStatus: Adb (USB debugging) enabled or disabled on device + // (Read-only) + AdbStatus bool `json:"adbStatus,omitempty"` + + // Applications: List of applications installed on Mobile Device + Applications []*MobileDeviceApplications `json:"applications,omitempty"` + + // BasebandVersion: Mobile Device Baseband version (Read-only) + BasebandVersion string `json:"basebandVersion,omitempty"` + + // BootloaderVersion: Mobile Device Bootloader version (Read-only) + BootloaderVersion string `json:"bootloaderVersion,omitempty"` + + // Brand: Mobile Device Brand (Read-only) + Brand string `json:"brand,omitempty"` + + // BuildNumber: Mobile Device Build number (Read-only) + BuildNumber string `json:"buildNumber,omitempty"` + + // DefaultLanguage: The default locale used on the Mobile Device + // (Read-only) + DefaultLanguage string `json:"defaultLanguage,omitempty"` + + // DeveloperOptionsStatus: Developer options enabled or disabled on + // device (Read-only) + DeveloperOptionsStatus bool `json:"developerOptionsStatus,omitempty"` + + // DeviceCompromisedStatus: Mobile Device compromised status (Read-only) + DeviceCompromisedStatus string `json:"deviceCompromisedStatus,omitempty"` + + // DeviceId: Mobile Device serial number (Read-only) + DeviceId string `json:"deviceId,omitempty"` + + // DevicePasswordStatus: DevicePasswordStatus (Read-only) + DevicePasswordStatus string `json:"devicePasswordStatus,omitempty"` + + // Email: List of owner user's email addresses (Read-only) + Email []string `json:"email,omitempty"` + + // EncryptionStatus: Mobile Device Encryption Status (Read-only) + EncryptionStatus string `json:"encryptionStatus,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // FirstSync: Date and time the device was first synchronized with the + // policy settings in the G Suite administrator control panel + // (Read-only) + FirstSync string `json:"firstSync,omitempty"` + + // Hardware: Mobile Device Hardware (Read-only) + Hardware string `json:"hardware,omitempty"` + + // HardwareId: Mobile Device Hardware Id (Read-only) + HardwareId string `json:"hardwareId,omitempty"` + + // Imei: Mobile Device IMEI number (Read-only) + Imei string `json:"imei,omitempty"` + + // KernelVersion: Mobile Device Kernel version (Read-only) + KernelVersion string `json:"kernelVersion,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // LastSync: Date and time the device was last synchronized with the + // policy settings in the G Suite administrator control panel + // (Read-only) + LastSync string `json:"lastSync,omitempty"` + + // ManagedAccountIsOnOwnerProfile: Boolean indicating if this account is + // on owner/primary profile or not (Read-only) + ManagedAccountIsOnOwnerProfile bool `json:"managedAccountIsOnOwnerProfile,omitempty"` + + // Manufacturer: Mobile Device manufacturer (Read-only) + Manufacturer string `json:"manufacturer,omitempty"` + + // Meid: Mobile Device MEID number (Read-only) + Meid string `json:"meid,omitempty"` + + // Model: Name of the model of the device + Model string `json:"model,omitempty"` + + // Name: List of owner user's names (Read-only) + Name []string `json:"name,omitempty"` + + // NetworkOperator: Mobile Device mobile or network operator (if + // available) (Read-only) + NetworkOperator string `json:"networkOperator,omitempty"` + + // Os: Name of the mobile operating system + Os string `json:"os,omitempty"` + + // OtherAccountsInfo: List of accounts added on device (Read-only) + OtherAccountsInfo []string `json:"otherAccountsInfo,omitempty"` + + // Privilege: DMAgentPermission (Read-only) + Privilege string `json:"privilege,omitempty"` + + // ReleaseVersion: Mobile Device release version version (Read-only) + ReleaseVersion string `json:"releaseVersion,omitempty"` + + // ResourceId: Unique identifier of Mobile Device (Read-only) + ResourceId string `json:"resourceId,omitempty"` + + // SecurityPatchLevel: Mobile Device Security patch level (Read-only) + SecurityPatchLevel int64 `json:"securityPatchLevel,omitempty,string"` + + // SerialNumber: Mobile Device SSN or Serial Number (Read-only) + SerialNumber string `json:"serialNumber,omitempty"` + + // Status: Status of the device (Read-only) + Status string `json:"status,omitempty"` + + // SupportsWorkProfile: Work profile supported on device (Read-only) + SupportsWorkProfile bool `json:"supportsWorkProfile,omitempty"` + + // Type: The type of device (Read-only) + Type string `json:"type,omitempty"` + + // UnknownSourcesStatus: Unknown sources enabled or disabled on device + // (Read-only) + UnknownSourcesStatus bool `json:"unknownSourcesStatus,omitempty"` + + // UserAgent: Mobile Device user agent + UserAgent string `json:"userAgent,omitempty"` + + // WifiMacAddress: Mobile Device WiFi MAC address (Read-only) + WifiMacAddress string `json:"wifiMacAddress,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "AdbStatus") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "AdbStatus") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *MobileDevice) MarshalJSON() ([]byte, error) { + type NoMethod MobileDevice + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type MobileDeviceApplications struct { + // DisplayName: Display name of application + DisplayName string `json:"displayName,omitempty"` + + // PackageName: Package name of application + PackageName string `json:"packageName,omitempty"` + + // Permission: List of Permissions for application + Permission []string `json:"permission,omitempty"` + + // VersionCode: Version code of application + VersionCode int64 `json:"versionCode,omitempty"` + + // VersionName: Version name of application + VersionName string `json:"versionName,omitempty"` + + // ForceSendFields is a list of field names (e.g. "DisplayName") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "DisplayName") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *MobileDeviceApplications) MarshalJSON() ([]byte, error) { + type NoMethod MobileDeviceApplications + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// MobileDeviceAction: JSON request template for firing commands on +// Mobile Device in Directory Devices API. +type MobileDeviceAction struct { + // Action: Action to be taken on the Mobile Device + Action string `json:"action,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Action") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Action") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *MobileDeviceAction) MarshalJSON() ([]byte, error) { + type NoMethod MobileDeviceAction + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// MobileDevices: JSON response template for List Mobile Devices +// operation in Directory API. +type MobileDevices struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // Mobiledevices: List of Mobile Device objects. + Mobiledevices []*MobileDevice `json:"mobiledevices,omitempty"` + + // NextPageToken: Token used to access next page of this result. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *MobileDevices) MarshalJSON() ([]byte, error) { + type NoMethod MobileDevices + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Notification: Template for a notification resource. +type Notification struct { + // Body: Body of the notification (Read-only) + Body string `json:"body,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // FromAddress: Address from which the notification is received + // (Read-only) + FromAddress string `json:"fromAddress,omitempty"` + + // IsUnread: Boolean indicating whether the notification is unread or + // not. + IsUnread bool `json:"isUnread,omitempty"` + + // Kind: The type of the resource. + Kind string `json:"kind,omitempty"` + + NotificationId string `json:"notificationId,omitempty"` + + // SendTime: Time at which notification was sent (Read-only) + SendTime string `json:"sendTime,omitempty"` + + // Subject: Subject of the notification (Read-only) + Subject string `json:"subject,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Body") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Body") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Notification) MarshalJSON() ([]byte, error) { + type NoMethod Notification + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Notifications: Template for notifications list response. +type Notifications struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Items: List of notifications in this page. + Items []*Notification `json:"items,omitempty"` + + // Kind: The type of the resource. + Kind string `json:"kind,omitempty"` + + // NextPageToken: Token for fetching the next page of notifications. + NextPageToken string `json:"nextPageToken,omitempty"` + + // UnreadNotificationsCount: Number of unread notification for the + // domain. + UnreadNotificationsCount int64 `json:"unreadNotificationsCount,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Notifications) MarshalJSON() ([]byte, error) { + type NoMethod Notifications + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// OrgUnit: JSON template for Org Unit resource in Directory API. +type OrgUnit struct { + // BlockInheritance: Should block inheritance + BlockInheritance bool `json:"blockInheritance,omitempty"` + + // Description: Description of OrgUnit + Description string `json:"description,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // Name: Name of OrgUnit + Name string `json:"name,omitempty"` + + // OrgUnitId: Id of OrgUnit + OrgUnitId string `json:"orgUnitId,omitempty"` + + // OrgUnitPath: Path of OrgUnit + OrgUnitPath string `json:"orgUnitPath,omitempty"` + + // ParentOrgUnitId: Id of parent OrgUnit + ParentOrgUnitId string `json:"parentOrgUnitId,omitempty"` + + // ParentOrgUnitPath: Path of parent OrgUnit + ParentOrgUnitPath string `json:"parentOrgUnitPath,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "BlockInheritance") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "BlockInheritance") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *OrgUnit) MarshalJSON() ([]byte, error) { + type NoMethod OrgUnit + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// OrgUnits: JSON response template for List Organization Units +// operation in Directory API. +type OrgUnits struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // OrganizationUnits: List of user objects. + OrganizationUnits []*OrgUnit `json:"organizationUnits,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *OrgUnits) MarshalJSON() ([]byte, error) { + type NoMethod OrgUnits + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Privilege: JSON template for privilege resource in Directory API. +type Privilege struct { + // ChildPrivileges: A list of child privileges. Privileges for a service + // form a tree. Each privilege can have a list of child privileges; this + // list is empty for a leaf privilege. + ChildPrivileges []*Privilege `json:"childPrivileges,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // IsOuScopable: If the privilege can be restricted to an organization + // unit. + IsOuScopable bool `json:"isOuScopable,omitempty"` + + // Kind: The type of the API resource. This is always + // admin#directory#privilege. + Kind string `json:"kind,omitempty"` + + // PrivilegeName: The name of the privilege. + PrivilegeName string `json:"privilegeName,omitempty"` + + // ServiceId: The obfuscated ID of the service this privilege is for. + // This value is returned with Privileges.list(). + ServiceId string `json:"serviceId,omitempty"` + + // ServiceName: The name of the service this privilege is for. + ServiceName string `json:"serviceName,omitempty"` + + // ForceSendFields is a list of field names (e.g. "ChildPrivileges") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "ChildPrivileges") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *Privilege) MarshalJSON() ([]byte, error) { + type NoMethod Privilege + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Privileges: JSON response template for List privileges operation in +// Directory API. +type Privileges struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Items: A list of Privilege resources. + Items []*Privilege `json:"items,omitempty"` + + // Kind: The type of the API resource. This is always + // admin#directory#privileges. + Kind string `json:"kind,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Privileges) MarshalJSON() ([]byte, error) { + type NoMethod Privileges + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Role: JSON template for role resource in Directory API. +type Role struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // IsSuperAdminRole: Returns true if the role is a super admin role. + IsSuperAdminRole bool `json:"isSuperAdminRole,omitempty"` + + // IsSystemRole: Returns true if this is a pre-defined system role. + IsSystemRole bool `json:"isSystemRole,omitempty"` + + // Kind: The type of the API resource. This is always + // admin#directory#role. + Kind string `json:"kind,omitempty"` + + // RoleDescription: A short description of the role. + RoleDescription string `json:"roleDescription,omitempty"` + + // RoleId: ID of the role. + RoleId int64 `json:"roleId,omitempty,string"` + + // RoleName: Name of the role. + RoleName string `json:"roleName,omitempty"` + + // RolePrivileges: The set of privileges that are granted to this role. + RolePrivileges []*RoleRolePrivileges `json:"rolePrivileges,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Role) MarshalJSON() ([]byte, error) { + type NoMethod Role + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type RoleRolePrivileges struct { + // PrivilegeName: The name of the privilege. + PrivilegeName string `json:"privilegeName,omitempty"` + + // ServiceId: The obfuscated ID of the service this privilege is for. + // This value is returned with Privileges.list(). + ServiceId string `json:"serviceId,omitempty"` + + // ForceSendFields is a list of field names (e.g. "PrivilegeName") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "PrivilegeName") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *RoleRolePrivileges) MarshalJSON() ([]byte, error) { + type NoMethod RoleRolePrivileges + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// RoleAssignment: JSON template for roleAssignment resource in +// Directory API. +type RoleAssignment struct { + // AssignedTo: The unique ID of the user this role is assigned to. + AssignedTo string `json:"assignedTo,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: The type of the API resource. This is always + // admin#directory#roleAssignment. + Kind string `json:"kind,omitempty"` + + // OrgUnitId: If the role is restricted to an organization unit, this + // contains the ID for the organization unit the exercise of this role + // is restricted to. + OrgUnitId string `json:"orgUnitId,omitempty"` + + // RoleAssignmentId: ID of this roleAssignment. + RoleAssignmentId int64 `json:"roleAssignmentId,omitempty,string"` + + // RoleId: The ID of the role that is assigned. + RoleId int64 `json:"roleId,omitempty,string"` + + // ScopeType: The scope in which this role is assigned. Possible values + // are: + // - CUSTOMER + // - ORG_UNIT + ScopeType string `json:"scopeType,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "AssignedTo") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "AssignedTo") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *RoleAssignment) MarshalJSON() ([]byte, error) { + type NoMethod RoleAssignment + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// RoleAssignments: JSON response template for List roleAssignments +// operation in Directory API. +type RoleAssignments struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Items: A list of RoleAssignment resources. + Items []*RoleAssignment `json:"items,omitempty"` + + // Kind: The type of the API resource. This is always + // admin#directory#roleAssignments. + Kind string `json:"kind,omitempty"` + + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *RoleAssignments) MarshalJSON() ([]byte, error) { + type NoMethod RoleAssignments + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Roles: JSON response template for List roles operation in Directory +// API. +type Roles struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Items: A list of Role resources. + Items []*Role `json:"items,omitempty"` + + // Kind: The type of the API resource. This is always + // admin#directory#roles. + Kind string `json:"kind,omitempty"` + + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Roles) MarshalJSON() ([]byte, error) { + type NoMethod Roles + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Schema: JSON template for Schema resource in Directory API. +type Schema struct { + // DisplayName: Display name for the schema. + DisplayName string `json:"displayName,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Fields: Fields of Schema + Fields []*SchemaFieldSpec `json:"fields,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // SchemaId: Unique identifier of Schema (Read-only) + SchemaId string `json:"schemaId,omitempty"` + + // SchemaName: Schema name + SchemaName string `json:"schemaName,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "DisplayName") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "DisplayName") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Schema) MarshalJSON() ([]byte, error) { + type NoMethod Schema + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// SchemaFieldSpec: JSON template for FieldSpec resource for Schemas in +// Directory API. +type SchemaFieldSpec struct { + // DisplayName: Display Name of the field. + DisplayName string `json:"displayName,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // FieldId: Unique identifier of Field (Read-only) + FieldId string `json:"fieldId,omitempty"` + + // FieldName: Name of the field. + FieldName string `json:"fieldName,omitempty"` + + // FieldType: Type of the field. + FieldType string `json:"fieldType,omitempty"` + + // Indexed: Boolean specifying whether the field is indexed or not. + // + // Default: true + Indexed *bool `json:"indexed,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // MultiValued: Boolean specifying whether this is a multi-valued field + // or not. + MultiValued bool `json:"multiValued,omitempty"` + + // NumericIndexingSpec: Indexing spec for a numeric field. By default, + // only exact match queries will be supported for numeric fields. + // Setting the numericIndexingSpec allows range queries to be supported. + NumericIndexingSpec *SchemaFieldSpecNumericIndexingSpec `json:"numericIndexingSpec,omitempty"` + + // ReadAccessType: Read ACLs on the field specifying who can view values + // of this field. Valid values are "ALL_DOMAIN_USERS" and + // "ADMINS_AND_SELF". + ReadAccessType string `json:"readAccessType,omitempty"` + + // ForceSendFields is a list of field names (e.g. "DisplayName") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "DisplayName") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *SchemaFieldSpec) MarshalJSON() ([]byte, error) { + type NoMethod SchemaFieldSpec + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// SchemaFieldSpecNumericIndexingSpec: Indexing spec for a numeric +// field. By default, only exact match queries will be supported for +// numeric fields. Setting the numericIndexingSpec allows range queries +// to be supported. +type SchemaFieldSpecNumericIndexingSpec struct { + // MaxValue: Maximum value of this field. This is meant to be indicative + // rather than enforced. Values outside this range will still be + // indexed, but search may not be as performant. + MaxValue float64 `json:"maxValue,omitempty"` + + // MinValue: Minimum value of this field. This is meant to be indicative + // rather than enforced. Values outside this range will still be + // indexed, but search may not be as performant. + MinValue float64 `json:"minValue,omitempty"` + + // ForceSendFields is a list of field names (e.g. "MaxValue") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "MaxValue") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *SchemaFieldSpecNumericIndexingSpec) MarshalJSON() ([]byte, error) { + type NoMethod SchemaFieldSpecNumericIndexingSpec + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +func (s *SchemaFieldSpecNumericIndexingSpec) UnmarshalJSON(data []byte) error { + type NoMethod SchemaFieldSpecNumericIndexingSpec + var s1 struct { + MaxValue gensupport.JSONFloat64 `json:"maxValue"` + MinValue gensupport.JSONFloat64 `json:"minValue"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.MaxValue = float64(s1.MaxValue) + s.MinValue = float64(s1.MinValue) + return nil +} + +// Schemas: JSON response template for List Schema operation in +// Directory API. +type Schemas struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // Schemas: List of UserSchema objects. + Schemas []*Schema `json:"schemas,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Schemas) MarshalJSON() ([]byte, error) { + type NoMethod Schemas + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Token: JSON template for token resource in Directory API. +type Token struct { + // Anonymous: Whether the application is registered with Google. The + // value is true if the application has an anonymous Client ID. + Anonymous bool `json:"anonymous,omitempty"` + + // ClientId: The Client ID of the application the token is issued to. + ClientId string `json:"clientId,omitempty"` + + // DisplayText: The displayable name of the application the token is + // issued to. + DisplayText string `json:"displayText,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: The type of the API resource. This is always + // admin#directory#token. + Kind string `json:"kind,omitempty"` + + // NativeApp: Whether the token is issued to an installed application. + // The value is true if the application is installed to a desktop or + // mobile device. + NativeApp bool `json:"nativeApp,omitempty"` + + // Scopes: A list of authorization scopes the application is granted. + Scopes []string `json:"scopes,omitempty"` + + // UserKey: The unique ID of the user that issued the token. + UserKey string `json:"userKey,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Anonymous") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Anonymous") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Token) MarshalJSON() ([]byte, error) { + type NoMethod Token + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Tokens: JSON response template for List tokens operation in Directory +// API. +type Tokens struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Items: A list of Token resources. + Items []*Token `json:"items,omitempty"` + + // Kind: The type of the API resource. This is always + // admin#directory#tokenList. + Kind string `json:"kind,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Tokens) MarshalJSON() ([]byte, error) { + type NoMethod Tokens + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// TrustedAppId: JSON template for Trusted App Ids Resource object in +// Directory API. +type TrustedAppId struct { + // AndroidPackageName: Android package name. + AndroidPackageName string `json:"androidPackageName,omitempty"` + + // CertificateHashSHA1: SHA1 signature of the app certificate. + CertificateHashSHA1 string `json:"certificateHashSHA1,omitempty"` + + // CertificateHashSHA256: SHA256 signature of the app certificate. + CertificateHashSHA256 string `json:"certificateHashSHA256,omitempty"` + + Etag string `json:"etag,omitempty"` + + // Kind: Identifies the resource as a trusted AppId. + Kind string `json:"kind,omitempty"` + + // ForceSendFields is a list of field names (e.g. "AndroidPackageName") + // to unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "AndroidPackageName") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *TrustedAppId) MarshalJSON() ([]byte, error) { + type NoMethod TrustedAppId + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// TrustedApps: JSON template for Trusted Apps response object of a user +// in Directory API. +type TrustedApps struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Identifies the resource as trusted apps response. + Kind string `json:"kind,omitempty"` + + NextPageToken string `json:"nextPageToken,omitempty"` + + // TrustedApps: Trusted Apps list. + TrustedApps []*TrustedAppId `json:"trustedApps,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TrustedApps) MarshalJSON() ([]byte, error) { + type NoMethod TrustedApps + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// User: JSON template for User object in Directory API. +type User struct { + Addresses interface{} `json:"addresses,omitempty"` + + // AgreedToTerms: Indicates if user has agreed to terms (Read-only) + AgreedToTerms bool `json:"agreedToTerms,omitempty"` + + // Aliases: List of aliases (Read-only) + Aliases []string `json:"aliases,omitempty"` + + // Archived: Indicates if user is archived. + Archived bool `json:"archived,omitempty"` + + // ChangePasswordAtNextLogin: Boolean indicating if the user should + // change password in next login + ChangePasswordAtNextLogin bool `json:"changePasswordAtNextLogin,omitempty"` + + // CreationTime: User's G Suite account creation time. (Read-only) + CreationTime string `json:"creationTime,omitempty"` + + // CustomSchemas: Custom fields of the user. + CustomSchemas map[string]googleapi.RawMessage `json:"customSchemas,omitempty"` + + // CustomerId: CustomerId of User (Read-only) + CustomerId string `json:"customerId,omitempty"` + + DeletionTime string `json:"deletionTime,omitempty"` + + Emails interface{} `json:"emails,omitempty"` + + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + ExternalIds interface{} `json:"externalIds,omitempty"` + + Gender interface{} `json:"gender,omitempty"` + + // HashFunction: Hash function name for password. Supported are MD5, + // SHA-1 and crypt + HashFunction string `json:"hashFunction,omitempty"` + + // Id: Unique identifier of User (Read-only) + Id string `json:"id,omitempty"` + + Ims interface{} `json:"ims,omitempty"` + + // IncludeInGlobalAddressList: Boolean indicating if user is included in + // Global Address List + IncludeInGlobalAddressList bool `json:"includeInGlobalAddressList,omitempty"` + + // IpWhitelisted: Boolean indicating if ip is whitelisted + IpWhitelisted bool `json:"ipWhitelisted,omitempty"` + + // IsAdmin: Boolean indicating if the user is admin (Read-only) + IsAdmin bool `json:"isAdmin,omitempty"` + + // IsDelegatedAdmin: Boolean indicating if the user is delegated admin + // (Read-only) + IsDelegatedAdmin bool `json:"isDelegatedAdmin,omitempty"` + + // IsEnforcedIn2Sv: Is 2-step verification enforced (Read-only) + IsEnforcedIn2Sv bool `json:"isEnforcedIn2Sv,omitempty"` + + // IsEnrolledIn2Sv: Is enrolled in 2-step verification (Read-only) + IsEnrolledIn2Sv bool `json:"isEnrolledIn2Sv,omitempty"` + + // IsMailboxSetup: Is mailbox setup (Read-only) + IsMailboxSetup bool `json:"isMailboxSetup,omitempty"` + + Keywords interface{} `json:"keywords,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + Languages interface{} `json:"languages,omitempty"` + + // LastLoginTime: User's last login time. (Read-only) + LastLoginTime string `json:"lastLoginTime,omitempty"` + + Locations interface{} `json:"locations,omitempty"` + + // Name: User's name + Name *UserName `json:"name,omitempty"` + + // NonEditableAliases: List of non editable aliases (Read-only) + NonEditableAliases []string `json:"nonEditableAliases,omitempty"` + + Notes interface{} `json:"notes,omitempty"` + + // OrgUnitPath: OrgUnit of User + OrgUnitPath string `json:"orgUnitPath,omitempty"` + + Organizations interface{} `json:"organizations,omitempty"` + + // Password: User's password + Password string `json:"password,omitempty"` + + Phones interface{} `json:"phones,omitempty"` + + PosixAccounts interface{} `json:"posixAccounts,omitempty"` + + // PrimaryEmail: username of User + PrimaryEmail string `json:"primaryEmail,omitempty"` + + // RecoveryEmail: Recovery email of the user. + RecoveryEmail string `json:"recoveryEmail,omitempty"` + + // RecoveryPhone: Recovery phone of the user. The phone number must be + // in the E.164 format, starting with the plus sign (+). Example: + // +16506661212. + RecoveryPhone string `json:"recoveryPhone,omitempty"` + + Relations interface{} `json:"relations,omitempty"` + + SshPublicKeys interface{} `json:"sshPublicKeys,omitempty"` + + // Suspended: Indicates if user is suspended. + Suspended bool `json:"suspended,omitempty"` + + // SuspensionReason: Suspension reason if user is suspended (Read-only) + SuspensionReason string `json:"suspensionReason,omitempty"` + + // ThumbnailPhotoEtag: ETag of the user's photo (Read-only) + ThumbnailPhotoEtag string `json:"thumbnailPhotoEtag,omitempty"` + + // ThumbnailPhotoUrl: Photo Url of the user (Read-only) + ThumbnailPhotoUrl string `json:"thumbnailPhotoUrl,omitempty"` + + Websites interface{} `json:"websites,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Addresses") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Addresses") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *User) MarshalJSON() ([]byte, error) { + type NoMethod User + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserAbout: JSON template for About (notes) of a user in Directory +// API. +type UserAbout struct { + // ContentType: About entry can have a type which indicates the content + // type. It can either be plain or html. By default, notes contents are + // assumed to contain plain text. + ContentType string `json:"contentType,omitempty"` + + // Value: Actual value of notes. + Value string `json:"value,omitempty"` + + // ForceSendFields is a list of field names (e.g. "ContentType") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "ContentType") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserAbout) MarshalJSON() ([]byte, error) { + type NoMethod UserAbout + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserAddress: JSON template for address. +type UserAddress struct { + // Country: Country. + Country string `json:"country,omitempty"` + + // CountryCode: Country code. + CountryCode string `json:"countryCode,omitempty"` + + // CustomType: Custom type. + CustomType string `json:"customType,omitempty"` + + // ExtendedAddress: Extended Address. + ExtendedAddress string `json:"extendedAddress,omitempty"` + + // Formatted: Formatted address. + Formatted string `json:"formatted,omitempty"` + + // Locality: Locality. + Locality string `json:"locality,omitempty"` + + // PoBox: Other parts of address. + PoBox string `json:"poBox,omitempty"` + + // PostalCode: Postal code. + PostalCode string `json:"postalCode,omitempty"` + + // Primary: If this is user's primary address. Only one entry could be + // marked as primary. + Primary bool `json:"primary,omitempty"` + + // Region: Region. + Region string `json:"region,omitempty"` + + // SourceIsStructured: User supplied address was structured. Structured + // addresses are NOT supported at this time. You might be able to write + // structured addresses, but any values will eventually be clobbered. + SourceIsStructured bool `json:"sourceIsStructured,omitempty"` + + // StreetAddress: Street. + StreetAddress string `json:"streetAddress,omitempty"` + + // Type: Each entry can have a type which indicates standard values of + // that entry. For example address could be of home, work etc. In + // addition to the standard type, an entry can have a custom type and + // can take any value. Such type should have the CUSTOM value as type + // and also have a customType value. + Type string `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Country") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Country") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserAddress) MarshalJSON() ([]byte, error) { + type NoMethod UserAddress + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserEmail: JSON template for an email. +type UserEmail struct { + // Address: Email id of the user. + Address string `json:"address,omitempty"` + + // CustomType: Custom Type. + CustomType string `json:"customType,omitempty"` + + // Primary: If this is user's primary email. Only one entry could be + // marked as primary. + Primary bool `json:"primary,omitempty"` + + // Type: Each entry can have a type which indicates standard types of + // that entry. For example email could be of home, work etc. In addition + // to the standard type, an entry can have a custom type and can take + // any value Such types should have the CUSTOM value as type and also + // have a customType value. + Type string `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Address") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Address") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserEmail) MarshalJSON() ([]byte, error) { + type NoMethod UserEmail + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserExternalId: JSON template for an externalId entry. +type UserExternalId struct { + // CustomType: Custom type. + CustomType string `json:"customType,omitempty"` + + // Type: The type of the Id. + Type string `json:"type,omitempty"` + + // Value: The value of the id. + Value string `json:"value,omitempty"` + + // ForceSendFields is a list of field names (e.g. "CustomType") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CustomType") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserExternalId) MarshalJSON() ([]byte, error) { + type NoMethod UserExternalId + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type UserGender struct { + // AddressMeAs: AddressMeAs. A human-readable string containing the + // proper way to refer to the profile owner by humans, for example + // "he/him/his" or "they/them/their". + AddressMeAs string `json:"addressMeAs,omitempty"` + + // CustomGender: Custom gender. + CustomGender string `json:"customGender,omitempty"` + + // Type: Gender. + Type string `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "AddressMeAs") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "AddressMeAs") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserGender) MarshalJSON() ([]byte, error) { + type NoMethod UserGender + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserIm: JSON template for instant messenger of an user. +type UserIm struct { + // CustomProtocol: Custom protocol. + CustomProtocol string `json:"customProtocol,omitempty"` + + // CustomType: Custom type. + CustomType string `json:"customType,omitempty"` + + // Im: Instant messenger id. + Im string `json:"im,omitempty"` + + // Primary: If this is user's primary im. Only one entry could be marked + // as primary. + Primary bool `json:"primary,omitempty"` + + // Protocol: Protocol used in the instant messenger. It should be one of + // the values from ImProtocolTypes map. Similar to type, it can take a + // CUSTOM value and specify the custom name in customProtocol field. + Protocol string `json:"protocol,omitempty"` + + // Type: Each entry can have a type which indicates standard types of + // that entry. For example instant messengers could be of home, work + // etc. In addition to the standard type, an entry can have a custom + // type and can take any value. Such types should have the CUSTOM value + // as type and also have a customType value. + Type string `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "CustomProtocol") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CustomProtocol") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *UserIm) MarshalJSON() ([]byte, error) { + type NoMethod UserIm + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserKeyword: JSON template for a keyword entry. +type UserKeyword struct { + // CustomType: Custom Type. + CustomType string `json:"customType,omitempty"` + + // Type: Each entry can have a type which indicates standard type of + // that entry. For example, keyword could be of type occupation or + // outlook. In addition to the standard type, an entry can have a custom + // type and can give it any name. Such types should have the CUSTOM + // value as type and also have a customType value. + Type string `json:"type,omitempty"` + + // Value: Keyword. + Value string `json:"value,omitempty"` + + // ForceSendFields is a list of field names (e.g. "CustomType") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CustomType") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserKeyword) MarshalJSON() ([]byte, error) { + type NoMethod UserKeyword + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserLanguage: JSON template for a language entry. +type UserLanguage struct { + // CustomLanguage: Other language. User can provide own language name if + // there is no corresponding Google III language code. If this is set + // LanguageCode can't be set + CustomLanguage string `json:"customLanguage,omitempty"` + + // LanguageCode: Language Code. Should be used for storing Google III + // LanguageCode string representation for language. Illegal values cause + // SchemaException. + LanguageCode string `json:"languageCode,omitempty"` + + // ForceSendFields is a list of field names (e.g. "CustomLanguage") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CustomLanguage") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *UserLanguage) MarshalJSON() ([]byte, error) { + type NoMethod UserLanguage + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserLocation: JSON template for a location entry. +type UserLocation struct { + // Area: Textual location. This is most useful for display purposes to + // concisely describe the location. For example, "Mountain View, CA", + // "Near Seattle", "US-NYC-9TH 9A209A". + Area string `json:"area,omitempty"` + + // BuildingId: Building Identifier. + BuildingId string `json:"buildingId,omitempty"` + + // CustomType: Custom Type. + CustomType string `json:"customType,omitempty"` + + // DeskCode: Most specific textual code of individual desk location. + DeskCode string `json:"deskCode,omitempty"` + + // FloorName: Floor name/number. + FloorName string `json:"floorName,omitempty"` + + // FloorSection: Floor section. More specific location within the floor. + // For example, if a floor is divided into sections "A", "B", and "C", + // this field would identify one of those values. + FloorSection string `json:"floorSection,omitempty"` + + // Type: Each entry can have a type which indicates standard types of + // that entry. For example location could be of types default and desk. + // In addition to standard type, an entry can have a custom type and can + // give it any name. Such types should have "custom" as type and also + // have a customType value. + Type string `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Area") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Area") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserLocation) MarshalJSON() ([]byte, error) { + type NoMethod UserLocation + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserMakeAdmin: JSON request template for setting/revoking admin +// status of a user in Directory API. +type UserMakeAdmin struct { + // Status: Boolean indicating new admin status of the user + Status bool `json:"status,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Status") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Status") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserMakeAdmin) MarshalJSON() ([]byte, error) { + type NoMethod UserMakeAdmin + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserName: JSON template for name of a user in Directory API. +type UserName struct { + // FamilyName: Last Name + FamilyName string `json:"familyName,omitempty"` + + // FullName: Full Name + FullName string `json:"fullName,omitempty"` + + // GivenName: First Name + GivenName string `json:"givenName,omitempty"` + + // ForceSendFields is a list of field names (e.g. "FamilyName") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "FamilyName") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserName) MarshalJSON() ([]byte, error) { + type NoMethod UserName + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserOrganization: JSON template for an organization entry. +type UserOrganization struct { + // CostCenter: The cost center of the users department. + CostCenter string `json:"costCenter,omitempty"` + + // CustomType: Custom type. + CustomType string `json:"customType,omitempty"` + + // Department: Department within the organization. + Department string `json:"department,omitempty"` + + // Description: Description of the organization. + Description string `json:"description,omitempty"` + + // Domain: The domain to which the organization belongs to. + Domain string `json:"domain,omitempty"` + + // FullTimeEquivalent: The full-time equivalent millipercent within the + // organization (100000 = 100%). + FullTimeEquivalent int64 `json:"fullTimeEquivalent,omitempty"` + + // Location: Location of the organization. This need not be fully + // qualified address. + Location string `json:"location,omitempty"` + + // Name: Name of the organization + Name string `json:"name,omitempty"` + + // Primary: If it user's primary organization. + Primary bool `json:"primary,omitempty"` + + // Symbol: Symbol of the organization. + Symbol string `json:"symbol,omitempty"` + + // Title: Title (designation) of the user in the organization. + Title string `json:"title,omitempty"` + + // Type: Each entry can have a type which indicates standard types of + // that entry. For example organization could be of school, work etc. In + // addition to the standard type, an entry can have a custom type and + // can give it any name. Such types should have the CUSTOM value as type + // and also have a CustomType value. + Type string `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "CostCenter") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CostCenter") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserOrganization) MarshalJSON() ([]byte, error) { + type NoMethod UserOrganization + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserPhone: JSON template for a phone entry. +type UserPhone struct { + // CustomType: Custom Type. + CustomType string `json:"customType,omitempty"` + + // Primary: If this is user's primary phone or not. + Primary bool `json:"primary,omitempty"` + + // Type: Each entry can have a type which indicates standard types of + // that entry. For example phone could be of home_fax, work, mobile etc. + // In addition to the standard type, an entry can have a custom type and + // can give it any name. Such types should have the CUSTOM value as type + // and also have a customType value. + Type string `json:"type,omitempty"` + + // Value: Phone number. + Value string `json:"value,omitempty"` + + // ForceSendFields is a list of field names (e.g. "CustomType") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CustomType") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserPhone) MarshalJSON() ([]byte, error) { + type NoMethod UserPhone + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserPhoto: JSON template for Photo object in Directory API. +type UserPhoto struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Height: Height in pixels of the photo + Height int64 `json:"height,omitempty"` + + // Id: Unique identifier of User (Read-only) + Id string `json:"id,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // MimeType: Mime Type of the photo + MimeType string `json:"mimeType,omitempty"` + + // PhotoData: Base64 encoded photo data + PhotoData string `json:"photoData,omitempty"` + + // PrimaryEmail: Primary email of User (Read-only) + PrimaryEmail string `json:"primaryEmail,omitempty"` + + // Width: Width in pixels of the photo + Width int64 `json:"width,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserPhoto) MarshalJSON() ([]byte, error) { + type NoMethod UserPhoto + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserPosixAccount: JSON template for a POSIX account entry. +// Description of the field family: go/fbs-posix. +type UserPosixAccount struct { + // AccountId: A POSIX account field identifier. + AccountId string `json:"accountId,omitempty"` + + // Gecos: The GECOS (user information) for this account. + Gecos string `json:"gecos,omitempty"` + + // Gid: The default group ID. + Gid uint64 `json:"gid,omitempty,string"` + + // HomeDirectory: The path to the home directory for this account. + HomeDirectory string `json:"homeDirectory,omitempty"` + + // OperatingSystemType: The operating system type for this account. + OperatingSystemType string `json:"operatingSystemType,omitempty"` + + // Primary: If this is user's primary account within the SystemId. + Primary bool `json:"primary,omitempty"` + + // Shell: The path to the login shell for this account. + Shell string `json:"shell,omitempty"` + + // SystemId: System identifier for which account Username or Uid apply + // to. + SystemId string `json:"systemId,omitempty"` + + // Uid: The POSIX compliant user ID. + Uid uint64 `json:"uid,omitempty,string"` + + // Username: The username of the account. + Username string `json:"username,omitempty"` + + // ForceSendFields is a list of field names (e.g. "AccountId") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "AccountId") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserPosixAccount) MarshalJSON() ([]byte, error) { + type NoMethod UserPosixAccount + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserRelation: JSON template for a relation entry. +type UserRelation struct { + // CustomType: Custom Type. + CustomType string `json:"customType,omitempty"` + + // Type: The relation of the user. Some of the possible values are + // mother, father, sister, brother, manager, assistant, partner. + Type string `json:"type,omitempty"` + + // Value: The name of the relation. + Value string `json:"value,omitempty"` + + // ForceSendFields is a list of field names (e.g. "CustomType") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CustomType") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserRelation) MarshalJSON() ([]byte, error) { + type NoMethod UserRelation + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserSshPublicKey: JSON template for a POSIX account entry. +type UserSshPublicKey struct { + // ExpirationTimeUsec: An expiration time in microseconds since epoch. + ExpirationTimeUsec int64 `json:"expirationTimeUsec,omitempty,string"` + + // Fingerprint: A SHA-256 fingerprint of the SSH public key. (Read-only) + Fingerprint string `json:"fingerprint,omitempty"` + + // Key: An SSH public key. + Key string `json:"key,omitempty"` + + // ForceSendFields is a list of field names (e.g. "ExpirationTimeUsec") + // to unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "ExpirationTimeUsec") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *UserSshPublicKey) MarshalJSON() ([]byte, error) { + type NoMethod UserSshPublicKey + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserUndelete: JSON request template to undelete a user in Directory +// API. +type UserUndelete struct { + // OrgUnitPath: OrgUnit of User + OrgUnitPath string `json:"orgUnitPath,omitempty"` + + // ForceSendFields is a list of field names (e.g. "OrgUnitPath") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "OrgUnitPath") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserUndelete) MarshalJSON() ([]byte, error) { + type NoMethod UserUndelete + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// UserWebsite: JSON template for a website entry. +type UserWebsite struct { + // CustomType: Custom Type. + CustomType string `json:"customType,omitempty"` + + // Primary: If this is user's primary website or not. + Primary bool `json:"primary,omitempty"` + + // Type: Each entry can have a type which indicates standard types of + // that entry. For example website could be of home, work, blog etc. In + // addition to the standard type, an entry can have a custom type and + // can give it any name. Such types should have the CUSTOM value as type + // and also have a customType value. + Type string `json:"type,omitempty"` + + // Value: Website. + Value string `json:"value,omitempty"` + + // ForceSendFields is a list of field names (e.g. "CustomType") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CustomType") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserWebsite) MarshalJSON() ([]byte, error) { + type NoMethod UserWebsite + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// Users: JSON response template for List Users operation in Apps +// Directory API. +type Users struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: Kind of resource this is. + Kind string `json:"kind,omitempty"` + + // NextPageToken: Token used to access next page of this result. + NextPageToken string `json:"nextPageToken,omitempty"` + + // TriggerEvent: Event that triggered this response (only used in case + // of Push Response) + TriggerEvent string `json:"trigger_event,omitempty"` + + // Users: List of user objects. + Users []*User `json:"users,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Users) MarshalJSON() ([]byte, error) { + type NoMethod Users + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// VerificationCode: JSON template for verification codes in Directory +// API. +type VerificationCode struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Kind: The type of the resource. This is always + // admin#directory#verificationCode. + Kind string `json:"kind,omitempty"` + + // UserId: The obfuscated unique ID of the user. + UserId string `json:"userId,omitempty"` + + // VerificationCode: A current verification code for the user. + // Invalidated or used verification codes are not returned as part of + // the result. + VerificationCode string `json:"verificationCode,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *VerificationCode) MarshalJSON() ([]byte, error) { + type NoMethod VerificationCode + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// VerificationCodes: JSON response template for List verification codes +// operation in Directory API. +type VerificationCodes struct { + // Etag: ETag of the resource. + Etag string `json:"etag,omitempty"` + + // Items: A list of verification code resources. + Items []*VerificationCode `json:"items,omitempty"` + + // Kind: The type of the resource. This is always + // admin#directory#verificationCodesList. + Kind string `json:"kind,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *VerificationCodes) MarshalJSON() ([]byte, error) { + type NoMethod VerificationCodes + raw := NoMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// method id "directory.asps.delete": + +type AspsDeleteCall struct { + s *Service + userKey string + codeId int64 + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Delete an ASP issued by a user. +func (r *AspsService) Delete(userKey string, codeId int64) *AspsDeleteCall { + c := &AspsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + c.codeId = codeId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *AspsDeleteCall) Fields(s ...googleapi.Field) *AspsDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *AspsDeleteCall) Context(ctx context.Context) *AspsDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *AspsDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *AspsDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/asps/{codeId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + "codeId": strconv.FormatInt(c.codeId, 10), + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.asps.delete" call. +func (c *AspsDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Delete an ASP issued by a user.", + // "httpMethod": "DELETE", + // "id": "directory.asps.delete", + // "parameterOrder": [ + // "userKey", + // "codeId" + // ], + // "parameters": { + // "codeId": { + // "description": "The unique ID of the ASP to be deleted.", + // "format": "int32", + // "location": "path", + // "required": true, + // "type": "integer" + // }, + // "userKey": { + // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/asps/{codeId}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user.security" + // ] + // } + +} + +// method id "directory.asps.get": + +type AspsGetCall struct { + s *Service + userKey string + codeId int64 + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Get information about an ASP issued by a user. +func (r *AspsService) Get(userKey string, codeId int64) *AspsGetCall { + c := &AspsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + c.codeId = codeId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *AspsGetCall) Fields(s ...googleapi.Field) *AspsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *AspsGetCall) IfNoneMatch(entityTag string) *AspsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *AspsGetCall) Context(ctx context.Context) *AspsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *AspsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *AspsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/asps/{codeId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + "codeId": strconv.FormatInt(c.codeId, 10), + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.asps.get" call. +// Exactly one of *Asp or error will be non-nil. Any non-2xx status code +// is an error. Response headers are in either +// *Asp.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was +// returned. +func (c *AspsGetCall) Do(opts ...googleapi.CallOption) (*Asp, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Asp{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Get information about an ASP issued by a user.", + // "httpMethod": "GET", + // "id": "directory.asps.get", + // "parameterOrder": [ + // "userKey", + // "codeId" + // ], + // "parameters": { + // "codeId": { + // "description": "The unique ID of the ASP.", + // "format": "int32", + // "location": "path", + // "required": true, + // "type": "integer" + // }, + // "userKey": { + // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/asps/{codeId}", + // "response": { + // "$ref": "Asp" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user.security" + // ] + // } + +} + +// method id "directory.asps.list": + +type AspsListCall struct { + s *Service + userKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: List the ASPs issued by a user. +func (r *AspsService) List(userKey string) *AspsListCall { + c := &AspsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *AspsListCall) Fields(s ...googleapi.Field) *AspsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *AspsListCall) IfNoneMatch(entityTag string) *AspsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *AspsListCall) Context(ctx context.Context) *AspsListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *AspsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *AspsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/asps") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.asps.list" call. +// Exactly one of *Asps or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Asps.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was +// returned. +func (c *AspsListCall) Do(opts ...googleapi.CallOption) (*Asps, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Asps{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "List the ASPs issued by a user.", + // "httpMethod": "GET", + // "id": "directory.asps.list", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/asps", + // "response": { + // "$ref": "Asps" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user.security" + // ] + // } + +} + +// method id "admin.channels.stop": + +type ChannelsStopCall struct { + s *Service + channel *Channel + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Stop: Stop watching resources through this channel +func (r *ChannelsService) Stop(channel *Channel) *ChannelsStopCall { + c := &ChannelsStopCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.channel = channel + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ChannelsStopCall) Fields(s ...googleapi.Field) *ChannelsStopCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ChannelsStopCall) Context(ctx context.Context) *ChannelsStopCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ChannelsStopCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ChannelsStopCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.channel) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "/admin/directory_v1/channels/stop") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "admin.channels.stop" call. +func (c *ChannelsStopCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Stop watching resources through this channel", + // "httpMethod": "POST", + // "id": "admin.channels.stop", + // "path": "/admin/directory_v1/channels/stop", + // "request": { + // "$ref": "Channel", + // "parameterName": "resource" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user", + // "https://www.googleapis.com/auth/admin.directory.user.alias", + // "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", + // "https://www.googleapis.com/auth/admin.directory.user.readonly" + // ] + // } + +} + +// method id "directory.chromeosdevices.action": + +type ChromeosdevicesActionCall struct { + s *Service + customerId string + resourceId string + chromeosdeviceaction *ChromeOsDeviceAction + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Action: Take action on Chrome OS Device +func (r *ChromeosdevicesService) Action(customerId string, resourceId string, chromeosdeviceaction *ChromeOsDeviceAction) *ChromeosdevicesActionCall { + c := &ChromeosdevicesActionCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.resourceId = resourceId + c.chromeosdeviceaction = chromeosdeviceaction + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ChromeosdevicesActionCall) Fields(s ...googleapi.Field) *ChromeosdevicesActionCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ChromeosdevicesActionCall) Context(ctx context.Context) *ChromeosdevicesActionCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ChromeosdevicesActionCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ChromeosdevicesActionCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.chromeosdeviceaction) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/chromeos/{resourceId}/action") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "resourceId": c.resourceId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.chromeosdevices.action" call. +func (c *ChromeosdevicesActionCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Take action on Chrome OS Device", + // "httpMethod": "POST", + // "id": "directory.chromeosdevices.action", + // "parameterOrder": [ + // "customerId", + // "resourceId" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "resourceId": { + // "description": "Immutable ID of Chrome OS Device", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/devices/chromeos/{resourceId}/action", + // "request": { + // "$ref": "ChromeOsDeviceAction" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.device.chromeos" + // ] + // } + +} + +// method id "directory.chromeosdevices.get": + +type ChromeosdevicesGetCall struct { + s *Service + customerId string + deviceId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieve Chrome OS Device +func (r *ChromeosdevicesService) Get(customerId string, deviceId string) *ChromeosdevicesGetCall { + c := &ChromeosdevicesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.deviceId = deviceId + return c +} + +// Projection sets the optional parameter "projection": Restrict +// information returned to a set of selected fields. +// +// Possible values: +// "BASIC" - Includes only the basic metadata fields (e.g., deviceId, +// serialNumber, status, and user) +// "FULL" - Includes all metadata fields +func (c *ChromeosdevicesGetCall) Projection(projection string) *ChromeosdevicesGetCall { + c.urlParams_.Set("projection", projection) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ChromeosdevicesGetCall) Fields(s ...googleapi.Field) *ChromeosdevicesGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *ChromeosdevicesGetCall) IfNoneMatch(entityTag string) *ChromeosdevicesGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ChromeosdevicesGetCall) Context(ctx context.Context) *ChromeosdevicesGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ChromeosdevicesGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ChromeosdevicesGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/chromeos/{deviceId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "deviceId": c.deviceId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.chromeosdevices.get" call. +// Exactly one of *ChromeOsDevice or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *ChromeOsDevice.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *ChromeosdevicesGetCall) Do(opts ...googleapi.CallOption) (*ChromeOsDevice, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &ChromeOsDevice{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve Chrome OS Device", + // "httpMethod": "GET", + // "id": "directory.chromeosdevices.get", + // "parameterOrder": [ + // "customerId", + // "deviceId" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "deviceId": { + // "description": "Immutable ID of Chrome OS Device", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projection": { + // "description": "Restrict information returned to a set of selected fields.", + // "enum": [ + // "BASIC", + // "FULL" + // ], + // "enumDescriptions": [ + // "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", + // "Includes all metadata fields" + // ], + // "location": "query", + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/devices/chromeos/{deviceId}", + // "response": { + // "$ref": "ChromeOsDevice" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.device.chromeos", + // "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly" + // ] + // } + +} + +// method id "directory.chromeosdevices.list": + +type ChromeosdevicesListCall struct { + s *Service + customerId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieve all Chrome OS Devices of a customer (paginated) +func (r *ChromeosdevicesService) List(customerId string) *ChromeosdevicesListCall { + c := &ChromeosdevicesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return. Max allowed value is 200. +func (c *ChromeosdevicesListCall) MaxResults(maxResults int64) *ChromeosdevicesListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// OrderBy sets the optional parameter "orderBy": Column to use for +// sorting results +// +// Possible values: +// "annotatedLocation" - Chromebook location as annotated by the +// administrator. +// "annotatedUser" - Chromebook user as annotated by administrator. +// "lastSync" - Chromebook last sync. +// "notes" - Chromebook notes as annotated by the administrator. +// "serialNumber" - Chromebook Serial Number. +// "status" - Chromebook status. +// "supportEndDate" - Chromebook support end date. +func (c *ChromeosdevicesListCall) OrderBy(orderBy string) *ChromeosdevicesListCall { + c.urlParams_.Set("orderBy", orderBy) + return c +} + +// OrgUnitPath sets the optional parameter "orgUnitPath": Full path of +// the organizational unit or its ID +func (c *ChromeosdevicesListCall) OrgUnitPath(orgUnitPath string) *ChromeosdevicesListCall { + c.urlParams_.Set("orgUnitPath", orgUnitPath) + return c +} + +// PageToken sets the optional parameter "pageToken": Token to specify +// next page in the list +func (c *ChromeosdevicesListCall) PageToken(pageToken string) *ChromeosdevicesListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Projection sets the optional parameter "projection": Restrict +// information returned to a set of selected fields. +// +// Possible values: +// "BASIC" - Includes only the basic metadata fields (e.g., deviceId, +// serialNumber, status, and user) +// "FULL" - Includes all metadata fields +func (c *ChromeosdevicesListCall) Projection(projection string) *ChromeosdevicesListCall { + c.urlParams_.Set("projection", projection) + return c +} + +// Query sets the optional parameter "query": Search string in the +// format given at +// http://support.google.com/chromeos/a/bin/answer.py?answer=1698333 +func (c *ChromeosdevicesListCall) Query(query string) *ChromeosdevicesListCall { + c.urlParams_.Set("query", query) + return c +} + +// SortOrder sets the optional parameter "sortOrder": Whether to return +// results in ascending or descending order. Only of use when orderBy is +// also used +// +// Possible values: +// "ASCENDING" - Ascending order. +// "DESCENDING" - Descending order. +func (c *ChromeosdevicesListCall) SortOrder(sortOrder string) *ChromeosdevicesListCall { + c.urlParams_.Set("sortOrder", sortOrder) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ChromeosdevicesListCall) Fields(s ...googleapi.Field) *ChromeosdevicesListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *ChromeosdevicesListCall) IfNoneMatch(entityTag string) *ChromeosdevicesListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ChromeosdevicesListCall) Context(ctx context.Context) *ChromeosdevicesListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ChromeosdevicesListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ChromeosdevicesListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/chromeos") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.chromeosdevices.list" call. +// Exactly one of *ChromeOsDevices or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *ChromeOsDevices.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *ChromeosdevicesListCall) Do(opts ...googleapi.CallOption) (*ChromeOsDevices, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &ChromeOsDevices{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve all Chrome OS Devices of a customer (paginated)", + // "httpMethod": "GET", + // "id": "directory.chromeosdevices.list", + // "parameterOrder": [ + // "customerId" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "maxResults": { + // "default": "100", + // "description": "Maximum number of results to return. Max allowed value is 200.", + // "format": "int32", + // "location": "query", + // "minimum": "1", + // "type": "integer" + // }, + // "orderBy": { + // "description": "Column to use for sorting results", + // "enum": [ + // "annotatedLocation", + // "annotatedUser", + // "lastSync", + // "notes", + // "serialNumber", + // "status", + // "supportEndDate" + // ], + // "enumDescriptions": [ + // "Chromebook location as annotated by the administrator.", + // "Chromebook user as annotated by administrator.", + // "Chromebook last sync.", + // "Chromebook notes as annotated by the administrator.", + // "Chromebook Serial Number.", + // "Chromebook status.", + // "Chromebook support end date." + // ], + // "location": "query", + // "type": "string" + // }, + // "orgUnitPath": { + // "description": "Full path of the organizational unit or its ID", + // "location": "query", + // "type": "string" + // }, + // "pageToken": { + // "description": "Token to specify next page in the list", + // "location": "query", + // "type": "string" + // }, + // "projection": { + // "description": "Restrict information returned to a set of selected fields.", + // "enum": [ + // "BASIC", + // "FULL" + // ], + // "enumDescriptions": [ + // "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", + // "Includes all metadata fields" + // ], + // "location": "query", + // "type": "string" + // }, + // "query": { + // "description": "Search string in the format given at http://support.google.com/chromeos/a/bin/answer.py?answer=1698333", + // "location": "query", + // "type": "string" + // }, + // "sortOrder": { + // "description": "Whether to return results in ascending or descending order. Only of use when orderBy is also used", + // "enum": [ + // "ASCENDING", + // "DESCENDING" + // ], + // "enumDescriptions": [ + // "Ascending order.", + // "Descending order." + // ], + // "location": "query", + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/devices/chromeos", + // "response": { + // "$ref": "ChromeOsDevices" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.device.chromeos", + // "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *ChromeosdevicesListCall) Pages(ctx context.Context, f func(*ChromeOsDevices) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "directory.chromeosdevices.moveDevicesToOu": + +type ChromeosdevicesMoveDevicesToOuCall struct { + s *Service + customerId string + chromeosmovedevicestoou *ChromeOsMoveDevicesToOu + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// MoveDevicesToOu: Move or insert multiple Chrome OS Devices to +// organizational unit +func (r *ChromeosdevicesService) MoveDevicesToOu(customerId string, orgUnitPath string, chromeosmovedevicestoou *ChromeOsMoveDevicesToOu) *ChromeosdevicesMoveDevicesToOuCall { + c := &ChromeosdevicesMoveDevicesToOuCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.urlParams_.Set("orgUnitPath", orgUnitPath) + c.chromeosmovedevicestoou = chromeosmovedevicestoou + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ChromeosdevicesMoveDevicesToOuCall) Fields(s ...googleapi.Field) *ChromeosdevicesMoveDevicesToOuCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ChromeosdevicesMoveDevicesToOuCall) Context(ctx context.Context) *ChromeosdevicesMoveDevicesToOuCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ChromeosdevicesMoveDevicesToOuCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ChromeosdevicesMoveDevicesToOuCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.chromeosmovedevicestoou) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/chromeos/moveDevicesToOu") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.chromeosdevices.moveDevicesToOu" call. +func (c *ChromeosdevicesMoveDevicesToOuCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Move or insert multiple Chrome OS Devices to organizational unit", + // "httpMethod": "POST", + // "id": "directory.chromeosdevices.moveDevicesToOu", + // "parameterOrder": [ + // "customerId", + // "orgUnitPath" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "orgUnitPath": { + // "description": "Full path of the target organizational unit or its ID", + // "location": "query", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/devices/chromeos/moveDevicesToOu", + // "request": { + // "$ref": "ChromeOsMoveDevicesToOu" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.device.chromeos" + // ] + // } + +} + +// method id "directory.chromeosdevices.patch": + +type ChromeosdevicesPatchCall struct { + s *Service + customerId string + deviceId string + chromeosdevice *ChromeOsDevice + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Update Chrome OS Device. This method supports patch semantics. +func (r *ChromeosdevicesService) Patch(customerId string, deviceId string, chromeosdevice *ChromeOsDevice) *ChromeosdevicesPatchCall { + c := &ChromeosdevicesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.deviceId = deviceId + c.chromeosdevice = chromeosdevice + return c +} + +// Projection sets the optional parameter "projection": Restrict +// information returned to a set of selected fields. +// +// Possible values: +// "BASIC" - Includes only the basic metadata fields (e.g., deviceId, +// serialNumber, status, and user) +// "FULL" - Includes all metadata fields +func (c *ChromeosdevicesPatchCall) Projection(projection string) *ChromeosdevicesPatchCall { + c.urlParams_.Set("projection", projection) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ChromeosdevicesPatchCall) Fields(s ...googleapi.Field) *ChromeosdevicesPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ChromeosdevicesPatchCall) Context(ctx context.Context) *ChromeosdevicesPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ChromeosdevicesPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ChromeosdevicesPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.chromeosdevice) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/chromeos/{deviceId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "deviceId": c.deviceId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.chromeosdevices.patch" call. +// Exactly one of *ChromeOsDevice or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *ChromeOsDevice.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *ChromeosdevicesPatchCall) Do(opts ...googleapi.CallOption) (*ChromeOsDevice, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &ChromeOsDevice{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Update Chrome OS Device. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "directory.chromeosdevices.patch", + // "parameterOrder": [ + // "customerId", + // "deviceId" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "deviceId": { + // "description": "Immutable ID of Chrome OS Device", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projection": { + // "description": "Restrict information returned to a set of selected fields.", + // "enum": [ + // "BASIC", + // "FULL" + // ], + // "enumDescriptions": [ + // "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", + // "Includes all metadata fields" + // ], + // "location": "query", + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/devices/chromeos/{deviceId}", + // "request": { + // "$ref": "ChromeOsDevice" + // }, + // "response": { + // "$ref": "ChromeOsDevice" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.device.chromeos" + // ] + // } + +} + +// method id "directory.chromeosdevices.update": + +type ChromeosdevicesUpdateCall struct { + s *Service + customerId string + deviceId string + chromeosdevice *ChromeOsDevice + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Update Chrome OS Device +func (r *ChromeosdevicesService) Update(customerId string, deviceId string, chromeosdevice *ChromeOsDevice) *ChromeosdevicesUpdateCall { + c := &ChromeosdevicesUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.deviceId = deviceId + c.chromeosdevice = chromeosdevice + return c +} + +// Projection sets the optional parameter "projection": Restrict +// information returned to a set of selected fields. +// +// Possible values: +// "BASIC" - Includes only the basic metadata fields (e.g., deviceId, +// serialNumber, status, and user) +// "FULL" - Includes all metadata fields +func (c *ChromeosdevicesUpdateCall) Projection(projection string) *ChromeosdevicesUpdateCall { + c.urlParams_.Set("projection", projection) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ChromeosdevicesUpdateCall) Fields(s ...googleapi.Field) *ChromeosdevicesUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ChromeosdevicesUpdateCall) Context(ctx context.Context) *ChromeosdevicesUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ChromeosdevicesUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ChromeosdevicesUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.chromeosdevice) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/chromeos/{deviceId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PUT", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "deviceId": c.deviceId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.chromeosdevices.update" call. +// Exactly one of *ChromeOsDevice or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *ChromeOsDevice.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *ChromeosdevicesUpdateCall) Do(opts ...googleapi.CallOption) (*ChromeOsDevice, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &ChromeOsDevice{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Update Chrome OS Device", + // "httpMethod": "PUT", + // "id": "directory.chromeosdevices.update", + // "parameterOrder": [ + // "customerId", + // "deviceId" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "deviceId": { + // "description": "Immutable ID of Chrome OS Device", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projection": { + // "description": "Restrict information returned to a set of selected fields.", + // "enum": [ + // "BASIC", + // "FULL" + // ], + // "enumDescriptions": [ + // "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", + // "Includes all metadata fields" + // ], + // "location": "query", + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/devices/chromeos/{deviceId}", + // "request": { + // "$ref": "ChromeOsDevice" + // }, + // "response": { + // "$ref": "ChromeOsDevice" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.device.chromeos" + // ] + // } + +} + +// method id "directory.customers.get": + +type CustomersGetCall struct { + s *Service + customerKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieves a customer. +func (r *CustomersService) Get(customerKey string) *CustomersGetCall { + c := &CustomersGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerKey = customerKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *CustomersGetCall) Fields(s ...googleapi.Field) *CustomersGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *CustomersGetCall) IfNoneMatch(entityTag string) *CustomersGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *CustomersGetCall) Context(ctx context.Context) *CustomersGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *CustomersGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CustomersGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customers/{customerKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerKey": c.customerKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.customers.get" call. +// Exactly one of *Customer or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Customer.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *CustomersGetCall) Do(opts ...googleapi.CallOption) (*Customer, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Customer{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a customer.", + // "httpMethod": "GET", + // "id": "directory.customers.get", + // "parameterOrder": [ + // "customerKey" + // ], + // "parameters": { + // "customerKey": { + // "description": "Id of the customer to be retrieved", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customers/{customerKey}", + // "response": { + // "$ref": "Customer" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.customer", + // "https://www.googleapis.com/auth/admin.directory.customer.readonly" + // ] + // } + +} + +// method id "directory.customers.patch": + +type CustomersPatchCall struct { + s *Service + customerKey string + customer *Customer + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates a customer. This method supports patch semantics. +func (r *CustomersService) Patch(customerKey string, customer *Customer) *CustomersPatchCall { + c := &CustomersPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerKey = customerKey + c.customer = customer + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *CustomersPatchCall) Fields(s ...googleapi.Field) *CustomersPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *CustomersPatchCall) Context(ctx context.Context) *CustomersPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *CustomersPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CustomersPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.customer) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customers/{customerKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerKey": c.customerKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.customers.patch" call. +// Exactly one of *Customer or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Customer.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *CustomersPatchCall) Do(opts ...googleapi.CallOption) (*Customer, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Customer{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates a customer. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "directory.customers.patch", + // "parameterOrder": [ + // "customerKey" + // ], + // "parameters": { + // "customerKey": { + // "description": "Id of the customer to be updated", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customers/{customerKey}", + // "request": { + // "$ref": "Customer" + // }, + // "response": { + // "$ref": "Customer" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.customer" + // ] + // } + +} + +// method id "directory.customers.update": + +type CustomersUpdateCall struct { + s *Service + customerKey string + customer *Customer + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Updates a customer. +func (r *CustomersService) Update(customerKey string, customer *Customer) *CustomersUpdateCall { + c := &CustomersUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerKey = customerKey + c.customer = customer + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *CustomersUpdateCall) Fields(s ...googleapi.Field) *CustomersUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *CustomersUpdateCall) Context(ctx context.Context) *CustomersUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *CustomersUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CustomersUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.customer) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customers/{customerKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PUT", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerKey": c.customerKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.customers.update" call. +// Exactly one of *Customer or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Customer.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *CustomersUpdateCall) Do(opts ...googleapi.CallOption) (*Customer, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Customer{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates a customer.", + // "httpMethod": "PUT", + // "id": "directory.customers.update", + // "parameterOrder": [ + // "customerKey" + // ], + // "parameters": { + // "customerKey": { + // "description": "Id of the customer to be updated", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customers/{customerKey}", + // "request": { + // "$ref": "Customer" + // }, + // "response": { + // "$ref": "Customer" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.customer" + // ] + // } + +} + +// method id "directory.domainAliases.delete": + +type DomainAliasesDeleteCall struct { + s *Service + customer string + domainAliasName string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes a Domain Alias of the customer. +func (r *DomainAliasesService) Delete(customer string, domainAliasName string) *DomainAliasesDeleteCall { + c := &DomainAliasesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.domainAliasName = domainAliasName + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DomainAliasesDeleteCall) Fields(s ...googleapi.Field) *DomainAliasesDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DomainAliasesDeleteCall) Context(ctx context.Context) *DomainAliasesDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DomainAliasesDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DomainAliasesDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domainaliases/{domainAliasName}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "domainAliasName": c.domainAliasName, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.domainAliases.delete" call. +func (c *DomainAliasesDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Deletes a Domain Alias of the customer.", + // "httpMethod": "DELETE", + // "id": "directory.domainAliases.delete", + // "parameterOrder": [ + // "customer", + // "domainAliasName" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "domainAliasName": { + // "description": "Name of domain alias to be retrieved.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/domainaliases/{domainAliasName}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.domain" + // ] + // } + +} + +// method id "directory.domainAliases.get": + +type DomainAliasesGetCall struct { + s *Service + customer string + domainAliasName string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieves a domain alias of the customer. +func (r *DomainAliasesService) Get(customer string, domainAliasName string) *DomainAliasesGetCall { + c := &DomainAliasesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.domainAliasName = domainAliasName + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DomainAliasesGetCall) Fields(s ...googleapi.Field) *DomainAliasesGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *DomainAliasesGetCall) IfNoneMatch(entityTag string) *DomainAliasesGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DomainAliasesGetCall) Context(ctx context.Context) *DomainAliasesGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DomainAliasesGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DomainAliasesGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domainaliases/{domainAliasName}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "domainAliasName": c.domainAliasName, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.domainAliases.get" call. +// Exactly one of *DomainAlias or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *DomainAlias.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *DomainAliasesGetCall) Do(opts ...googleapi.CallOption) (*DomainAlias, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &DomainAlias{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a domain alias of the customer.", + // "httpMethod": "GET", + // "id": "directory.domainAliases.get", + // "parameterOrder": [ + // "customer", + // "domainAliasName" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "domainAliasName": { + // "description": "Name of domain alias to be retrieved.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/domainaliases/{domainAliasName}", + // "response": { + // "$ref": "DomainAlias" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.domain", + // "https://www.googleapis.com/auth/admin.directory.domain.readonly" + // ] + // } + +} + +// method id "directory.domainAliases.insert": + +type DomainAliasesInsertCall struct { + s *Service + customer string + domainalias *DomainAlias + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Inserts a Domain alias of the customer. +func (r *DomainAliasesService) Insert(customer string, domainalias *DomainAlias) *DomainAliasesInsertCall { + c := &DomainAliasesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.domainalias = domainalias + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DomainAliasesInsertCall) Fields(s ...googleapi.Field) *DomainAliasesInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DomainAliasesInsertCall) Context(ctx context.Context) *DomainAliasesInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DomainAliasesInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DomainAliasesInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.domainalias) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domainaliases") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.domainAliases.insert" call. +// Exactly one of *DomainAlias or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *DomainAlias.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *DomainAliasesInsertCall) Do(opts ...googleapi.CallOption) (*DomainAlias, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &DomainAlias{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Inserts a Domain alias of the customer.", + // "httpMethod": "POST", + // "id": "directory.domainAliases.insert", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/domainaliases", + // "request": { + // "$ref": "DomainAlias" + // }, + // "response": { + // "$ref": "DomainAlias" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.domain" + // ] + // } + +} + +// method id "directory.domainAliases.list": + +type DomainAliasesListCall struct { + s *Service + customer string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists the domain aliases of the customer. +func (r *DomainAliasesService) List(customer string) *DomainAliasesListCall { + c := &DomainAliasesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + return c +} + +// ParentDomainName sets the optional parameter "parentDomainName": Name +// of the parent domain for which domain aliases are to be fetched. +func (c *DomainAliasesListCall) ParentDomainName(parentDomainName string) *DomainAliasesListCall { + c.urlParams_.Set("parentDomainName", parentDomainName) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DomainAliasesListCall) Fields(s ...googleapi.Field) *DomainAliasesListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *DomainAliasesListCall) IfNoneMatch(entityTag string) *DomainAliasesListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DomainAliasesListCall) Context(ctx context.Context) *DomainAliasesListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DomainAliasesListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DomainAliasesListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domainaliases") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.domainAliases.list" call. +// Exactly one of *DomainAliases or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *DomainAliases.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *DomainAliasesListCall) Do(opts ...googleapi.CallOption) (*DomainAliases, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &DomainAliases{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Lists the domain aliases of the customer.", + // "httpMethod": "GET", + // "id": "directory.domainAliases.list", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "parentDomainName": { + // "description": "Name of the parent domain for which domain aliases are to be fetched.", + // "location": "query", + // "type": "string" + // } + // }, + // "path": "customer/{customer}/domainaliases", + // "response": { + // "$ref": "DomainAliases" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.domain", + // "https://www.googleapis.com/auth/admin.directory.domain.readonly" + // ] + // } + +} + +// method id "directory.domains.delete": + +type DomainsDeleteCall struct { + s *Service + customer string + domainName string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes a domain of the customer. +func (r *DomainsService) Delete(customer string, domainName string) *DomainsDeleteCall { + c := &DomainsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.domainName = domainName + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DomainsDeleteCall) Fields(s ...googleapi.Field) *DomainsDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DomainsDeleteCall) Context(ctx context.Context) *DomainsDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DomainsDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DomainsDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domains/{domainName}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "domainName": c.domainName, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.domains.delete" call. +func (c *DomainsDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Deletes a domain of the customer.", + // "httpMethod": "DELETE", + // "id": "directory.domains.delete", + // "parameterOrder": [ + // "customer", + // "domainName" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "domainName": { + // "description": "Name of domain to be deleted", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/domains/{domainName}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.domain" + // ] + // } + +} + +// method id "directory.domains.get": + +type DomainsGetCall struct { + s *Service + customer string + domainName string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieves a domain of the customer. +func (r *DomainsService) Get(customer string, domainName string) *DomainsGetCall { + c := &DomainsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.domainName = domainName + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DomainsGetCall) Fields(s ...googleapi.Field) *DomainsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *DomainsGetCall) IfNoneMatch(entityTag string) *DomainsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DomainsGetCall) Context(ctx context.Context) *DomainsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DomainsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DomainsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domains/{domainName}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "domainName": c.domainName, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.domains.get" call. +// Exactly one of *Domains or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Domains.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *DomainsGetCall) Do(opts ...googleapi.CallOption) (*Domains, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Domains{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a domain of the customer.", + // "httpMethod": "GET", + // "id": "directory.domains.get", + // "parameterOrder": [ + // "customer", + // "domainName" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "domainName": { + // "description": "Name of domain to be retrieved", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/domains/{domainName}", + // "response": { + // "$ref": "Domains" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.domain", + // "https://www.googleapis.com/auth/admin.directory.domain.readonly" + // ] + // } + +} + +// method id "directory.domains.insert": + +type DomainsInsertCall struct { + s *Service + customer string + domains *Domains + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Inserts a domain of the customer. +func (r *DomainsService) Insert(customer string, domains *Domains) *DomainsInsertCall { + c := &DomainsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.domains = domains + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DomainsInsertCall) Fields(s ...googleapi.Field) *DomainsInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DomainsInsertCall) Context(ctx context.Context) *DomainsInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DomainsInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DomainsInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.domains) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domains") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.domains.insert" call. +// Exactly one of *Domains or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Domains.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *DomainsInsertCall) Do(opts ...googleapi.CallOption) (*Domains, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Domains{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Inserts a domain of the customer.", + // "httpMethod": "POST", + // "id": "directory.domains.insert", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/domains", + // "request": { + // "$ref": "Domains" + // }, + // "response": { + // "$ref": "Domains" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.domain" + // ] + // } + +} + +// method id "directory.domains.list": + +type DomainsListCall struct { + s *Service + customer string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists the domains of the customer. +func (r *DomainsService) List(customer string) *DomainsListCall { + c := &DomainsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DomainsListCall) Fields(s ...googleapi.Field) *DomainsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *DomainsListCall) IfNoneMatch(entityTag string) *DomainsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DomainsListCall) Context(ctx context.Context) *DomainsListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DomainsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DomainsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domains") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.domains.list" call. +// Exactly one of *Domains2 or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Domains2.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *DomainsListCall) Do(opts ...googleapi.CallOption) (*Domains2, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Domains2{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Lists the domains of the customer.", + // "httpMethod": "GET", + // "id": "directory.domains.list", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/domains", + // "response": { + // "$ref": "Domains2" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.domain", + // "https://www.googleapis.com/auth/admin.directory.domain.readonly" + // ] + // } + +} + +// method id "directory.groups.delete": + +type GroupsDeleteCall struct { + s *Service + groupKey string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Delete Group +func (r *GroupsService) Delete(groupKey string) *GroupsDeleteCall { + c := &GroupsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *GroupsDeleteCall) Fields(s ...googleapi.Field) *GroupsDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *GroupsDeleteCall) Context(ctx context.Context) *GroupsDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *GroupsDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *GroupsDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.groups.delete" call. +func (c *GroupsDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Delete Group", + // "httpMethod": "DELETE", + // "id": "directory.groups.delete", + // "parameterOrder": [ + // "groupKey" + // ], + // "parameters": { + // "groupKey": { + // "description": "Email or immutable ID of the group", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group" + // ] + // } + +} + +// method id "directory.groups.get": + +type GroupsGetCall struct { + s *Service + groupKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieve Group +func (r *GroupsService) Get(groupKey string) *GroupsGetCall { + c := &GroupsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *GroupsGetCall) Fields(s ...googleapi.Field) *GroupsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *GroupsGetCall) IfNoneMatch(entityTag string) *GroupsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *GroupsGetCall) Context(ctx context.Context) *GroupsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *GroupsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *GroupsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.groups.get" call. +// Exactly one of *Group or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Group.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *GroupsGetCall) Do(opts ...googleapi.CallOption) (*Group, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Group{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve Group", + // "httpMethod": "GET", + // "id": "directory.groups.get", + // "parameterOrder": [ + // "groupKey" + // ], + // "parameters": { + // "groupKey": { + // "description": "Email or immutable ID of the group", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}", + // "response": { + // "$ref": "Group" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group", + // "https://www.googleapis.com/auth/admin.directory.group.readonly" + // ] + // } + +} + +// method id "directory.groups.insert": + +type GroupsInsertCall struct { + s *Service + group *Group + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Create Group +func (r *GroupsService) Insert(group *Group) *GroupsInsertCall { + c := &GroupsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.group = group + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *GroupsInsertCall) Fields(s ...googleapi.Field) *GroupsInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *GroupsInsertCall) Context(ctx context.Context) *GroupsInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *GroupsInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *GroupsInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.group) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.groups.insert" call. +// Exactly one of *Group or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Group.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *GroupsInsertCall) Do(opts ...googleapi.CallOption) (*Group, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Group{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Create Group", + // "httpMethod": "POST", + // "id": "directory.groups.insert", + // "path": "groups", + // "request": { + // "$ref": "Group" + // }, + // "response": { + // "$ref": "Group" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group" + // ] + // } + +} + +// method id "directory.groups.list": + +type GroupsListCall struct { + s *Service + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieve all groups of a domain or of a user given a userKey +// (paginated) +func (r *GroupsService) List() *GroupsListCall { + c := &GroupsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + return c +} + +// Customer sets the optional parameter "customer": Immutable ID of the +// G Suite account. In case of multi-domain, to fetch all groups for a +// customer, fill this field instead of domain. +func (c *GroupsListCall) Customer(customer string) *GroupsListCall { + c.urlParams_.Set("customer", customer) + return c +} + +// Domain sets the optional parameter "domain": Name of the domain. Fill +// this field to get groups from only this domain. To return all groups +// in a multi-domain fill customer field instead. +func (c *GroupsListCall) Domain(domain string) *GroupsListCall { + c.urlParams_.Set("domain", domain) + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return. Max allowed value is 200. +func (c *GroupsListCall) MaxResults(maxResults int64) *GroupsListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// OrderBy sets the optional parameter "orderBy": Column to use for +// sorting results +// +// Possible values: +// "email" - Email of the group. +func (c *GroupsListCall) OrderBy(orderBy string) *GroupsListCall { + c.urlParams_.Set("orderBy", orderBy) + return c +} + +// PageToken sets the optional parameter "pageToken": Token to specify +// next page in the list +func (c *GroupsListCall) PageToken(pageToken string) *GroupsListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Query sets the optional parameter "query": Query string search. +// Should be of the form "". Complete documentation is at +// https://developers.google.com/admin-sdk/directory/v1/guides/search-groups +func (c *GroupsListCall) Query(query string) *GroupsListCall { + c.urlParams_.Set("query", query) + return c +} + +// SortOrder sets the optional parameter "sortOrder": Whether to return +// results in ascending or descending order. Only of use when orderBy is +// also used +// +// Possible values: +// "ASCENDING" - Ascending order. +// "DESCENDING" - Descending order. +func (c *GroupsListCall) SortOrder(sortOrder string) *GroupsListCall { + c.urlParams_.Set("sortOrder", sortOrder) + return c +} + +// UserKey sets the optional parameter "userKey": Email or immutable ID +// of the user if only those groups are to be listed, the given user is +// a member of. If it's an ID, it should match with the ID of the user +// object. +func (c *GroupsListCall) UserKey(userKey string) *GroupsListCall { + c.urlParams_.Set("userKey", userKey) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *GroupsListCall) Fields(s ...googleapi.Field) *GroupsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *GroupsListCall) IfNoneMatch(entityTag string) *GroupsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *GroupsListCall) Context(ctx context.Context) *GroupsListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *GroupsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *GroupsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.groups.list" call. +// Exactly one of *Groups or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Groups.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *GroupsListCall) Do(opts ...googleapi.CallOption) (*Groups, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Groups{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve all groups of a domain or of a user given a userKey (paginated)", + // "httpMethod": "GET", + // "id": "directory.groups.list", + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account. In case of multi-domain, to fetch all groups for a customer, fill this field instead of domain.", + // "location": "query", + // "type": "string" + // }, + // "domain": { + // "description": "Name of the domain. Fill this field to get groups from only this domain. To return all groups in a multi-domain fill customer field instead.", + // "location": "query", + // "type": "string" + // }, + // "maxResults": { + // "default": "200", + // "description": "Maximum number of results to return. Max allowed value is 200.", + // "format": "int32", + // "location": "query", + // "minimum": "1", + // "type": "integer" + // }, + // "orderBy": { + // "description": "Column to use for sorting results", + // "enum": [ + // "email" + // ], + // "enumDescriptions": [ + // "Email of the group." + // ], + // "location": "query", + // "type": "string" + // }, + // "pageToken": { + // "description": "Token to specify next page in the list", + // "location": "query", + // "type": "string" + // }, + // "query": { + // "description": "Query string search. Should be of the form \"\". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-groups", + // "location": "query", + // "type": "string" + // }, + // "sortOrder": { + // "description": "Whether to return results in ascending or descending order. Only of use when orderBy is also used", + // "enum": [ + // "ASCENDING", + // "DESCENDING" + // ], + // "enumDescriptions": [ + // "Ascending order.", + // "Descending order." + // ], + // "location": "query", + // "type": "string" + // }, + // "userKey": { + // "description": "Email or immutable ID of the user if only those groups are to be listed, the given user is a member of. If it's an ID, it should match with the ID of the user object.", + // "location": "query", + // "type": "string" + // } + // }, + // "path": "groups", + // "response": { + // "$ref": "Groups" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group", + // "https://www.googleapis.com/auth/admin.directory.group.readonly" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *GroupsListCall) Pages(ctx context.Context, f func(*Groups) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "directory.groups.patch": + +type GroupsPatchCall struct { + s *Service + groupKey string + group *Group + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Update Group. This method supports patch semantics. +func (r *GroupsService) Patch(groupKey string, group *Group) *GroupsPatchCall { + c := &GroupsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + c.group = group + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *GroupsPatchCall) Fields(s ...googleapi.Field) *GroupsPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *GroupsPatchCall) Context(ctx context.Context) *GroupsPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *GroupsPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *GroupsPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.group) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.groups.patch" call. +// Exactly one of *Group or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Group.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *GroupsPatchCall) Do(opts ...googleapi.CallOption) (*Group, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Group{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Update Group. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "directory.groups.patch", + // "parameterOrder": [ + // "groupKey" + // ], + // "parameters": { + // "groupKey": { + // "description": "Email or immutable ID of the group. If ID, it should match with id of group object", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}", + // "request": { + // "$ref": "Group" + // }, + // "response": { + // "$ref": "Group" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group" + // ] + // } + +} + +// method id "directory.groups.update": + +type GroupsUpdateCall struct { + s *Service + groupKey string + group *Group + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Update Group +func (r *GroupsService) Update(groupKey string, group *Group) *GroupsUpdateCall { + c := &GroupsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + c.group = group + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *GroupsUpdateCall) Fields(s ...googleapi.Field) *GroupsUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *GroupsUpdateCall) Context(ctx context.Context) *GroupsUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *GroupsUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *GroupsUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.group) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PUT", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.groups.update" call. +// Exactly one of *Group or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Group.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *GroupsUpdateCall) Do(opts ...googleapi.CallOption) (*Group, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Group{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Update Group", + // "httpMethod": "PUT", + // "id": "directory.groups.update", + // "parameterOrder": [ + // "groupKey" + // ], + // "parameters": { + // "groupKey": { + // "description": "Email or immutable ID of the group. If ID, it should match with id of group object", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}", + // "request": { + // "$ref": "Group" + // }, + // "response": { + // "$ref": "Group" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group" + // ] + // } + +} + +// method id "directory.groups.aliases.delete": + +type GroupsAliasesDeleteCall struct { + s *Service + groupKey string + alias string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Remove a alias for the group +func (r *GroupsAliasesService) Delete(groupKey string, alias string) *GroupsAliasesDeleteCall { + c := &GroupsAliasesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + c.alias = alias + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *GroupsAliasesDeleteCall) Fields(s ...googleapi.Field) *GroupsAliasesDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *GroupsAliasesDeleteCall) Context(ctx context.Context) *GroupsAliasesDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *GroupsAliasesDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *GroupsAliasesDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/aliases/{alias}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + "alias": c.alias, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.groups.aliases.delete" call. +func (c *GroupsAliasesDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Remove a alias for the group", + // "httpMethod": "DELETE", + // "id": "directory.groups.aliases.delete", + // "parameterOrder": [ + // "groupKey", + // "alias" + // ], + // "parameters": { + // "alias": { + // "description": "The alias to be removed", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "groupKey": { + // "description": "Email or immutable ID of the group", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}/aliases/{alias}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group" + // ] + // } + +} + +// method id "directory.groups.aliases.insert": + +type GroupsAliasesInsertCall struct { + s *Service + groupKey string + alias *Alias + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Add a alias for the group +func (r *GroupsAliasesService) Insert(groupKey string, alias *Alias) *GroupsAliasesInsertCall { + c := &GroupsAliasesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + c.alias = alias + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *GroupsAliasesInsertCall) Fields(s ...googleapi.Field) *GroupsAliasesInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *GroupsAliasesInsertCall) Context(ctx context.Context) *GroupsAliasesInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *GroupsAliasesInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *GroupsAliasesInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.alias) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/aliases") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.groups.aliases.insert" call. +// Exactly one of *Alias or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Alias.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *GroupsAliasesInsertCall) Do(opts ...googleapi.CallOption) (*Alias, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Alias{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Add a alias for the group", + // "httpMethod": "POST", + // "id": "directory.groups.aliases.insert", + // "parameterOrder": [ + // "groupKey" + // ], + // "parameters": { + // "groupKey": { + // "description": "Email or immutable ID of the group", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}/aliases", + // "request": { + // "$ref": "Alias" + // }, + // "response": { + // "$ref": "Alias" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group" + // ] + // } + +} + +// method id "directory.groups.aliases.list": + +type GroupsAliasesListCall struct { + s *Service + groupKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: List all aliases for a group +func (r *GroupsAliasesService) List(groupKey string) *GroupsAliasesListCall { + c := &GroupsAliasesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *GroupsAliasesListCall) Fields(s ...googleapi.Field) *GroupsAliasesListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *GroupsAliasesListCall) IfNoneMatch(entityTag string) *GroupsAliasesListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *GroupsAliasesListCall) Context(ctx context.Context) *GroupsAliasesListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *GroupsAliasesListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *GroupsAliasesListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/aliases") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.groups.aliases.list" call. +// Exactly one of *Aliases or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Aliases.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *GroupsAliasesListCall) Do(opts ...googleapi.CallOption) (*Aliases, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Aliases{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "List all aliases for a group", + // "httpMethod": "GET", + // "id": "directory.groups.aliases.list", + // "parameterOrder": [ + // "groupKey" + // ], + // "parameters": { + // "groupKey": { + // "description": "Email or immutable ID of the group", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}/aliases", + // "response": { + // "$ref": "Aliases" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group", + // "https://www.googleapis.com/auth/admin.directory.group.readonly" + // ], + // "supportsSubscription": true + // } + +} + +// method id "directory.members.delete": + +type MembersDeleteCall struct { + s *Service + groupKey string + memberKey string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Remove membership. +func (r *MembersService) Delete(groupKey string, memberKey string) *MembersDeleteCall { + c := &MembersDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + c.memberKey = memberKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *MembersDeleteCall) Fields(s ...googleapi.Field) *MembersDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *MembersDeleteCall) Context(ctx context.Context) *MembersDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *MembersDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *MembersDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/members/{memberKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + "memberKey": c.memberKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.members.delete" call. +func (c *MembersDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Remove membership.", + // "httpMethod": "DELETE", + // "id": "directory.members.delete", + // "parameterOrder": [ + // "groupKey", + // "memberKey" + // ], + // "parameters": { + // "groupKey": { + // "description": "Email or immutable ID of the group", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "memberKey": { + // "description": "Email or immutable ID of the member", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}/members/{memberKey}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group", + // "https://www.googleapis.com/auth/admin.directory.group.member" + // ] + // } + +} + +// method id "directory.members.get": + +type MembersGetCall struct { + s *Service + groupKey string + memberKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieve Group Member +func (r *MembersService) Get(groupKey string, memberKey string) *MembersGetCall { + c := &MembersGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + c.memberKey = memberKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *MembersGetCall) Fields(s ...googleapi.Field) *MembersGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *MembersGetCall) IfNoneMatch(entityTag string) *MembersGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *MembersGetCall) Context(ctx context.Context) *MembersGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *MembersGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *MembersGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/members/{memberKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + "memberKey": c.memberKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.members.get" call. +// Exactly one of *Member or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Member.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *MembersGetCall) Do(opts ...googleapi.CallOption) (*Member, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Member{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve Group Member", + // "httpMethod": "GET", + // "id": "directory.members.get", + // "parameterOrder": [ + // "groupKey", + // "memberKey" + // ], + // "parameters": { + // "groupKey": { + // "description": "Email or immutable ID of the group", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "memberKey": { + // "description": "Email or immutable ID of the member", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}/members/{memberKey}", + // "response": { + // "$ref": "Member" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group", + // "https://www.googleapis.com/auth/admin.directory.group.member", + // "https://www.googleapis.com/auth/admin.directory.group.member.readonly", + // "https://www.googleapis.com/auth/admin.directory.group.readonly" + // ] + // } + +} + +// method id "directory.members.hasMember": + +type MembersHasMemberCall struct { + s *Service + groupKey string + memberKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// HasMember: Checks whether the given user is a member of the group. +// Membership can be direct or nested. +func (r *MembersService) HasMember(groupKey string, memberKey string) *MembersHasMemberCall { + c := &MembersHasMemberCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + c.memberKey = memberKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *MembersHasMemberCall) Fields(s ...googleapi.Field) *MembersHasMemberCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *MembersHasMemberCall) IfNoneMatch(entityTag string) *MembersHasMemberCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *MembersHasMemberCall) Context(ctx context.Context) *MembersHasMemberCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *MembersHasMemberCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *MembersHasMemberCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/hasMember/{memberKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + "memberKey": c.memberKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.members.hasMember" call. +// Exactly one of *MembersHasMember or error will be non-nil. Any +// non-2xx status code is an error. Response headers are in either +// *MembersHasMember.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *MembersHasMemberCall) Do(opts ...googleapi.CallOption) (*MembersHasMember, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &MembersHasMember{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Checks whether the given user is a member of the group. Membership can be direct or nested.", + // "httpMethod": "GET", + // "id": "directory.members.hasMember", + // "parameterOrder": [ + // "groupKey", + // "memberKey" + // ], + // "parameters": { + // "groupKey": { + // "description": "Identifies the group in the API request. The value can be the group's email address, group alias, or the unique group ID.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "memberKey": { + // "description": "Identifies the user member in the API request. The value can be the user's primary email address, alias, or unique ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}/hasMember/{memberKey}", + // "response": { + // "$ref": "MembersHasMember" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group", + // "https://www.googleapis.com/auth/admin.directory.group.member", + // "https://www.googleapis.com/auth/admin.directory.group.member.readonly", + // "https://www.googleapis.com/auth/admin.directory.group.readonly" + // ] + // } + +} + +// method id "directory.members.insert": + +type MembersInsertCall struct { + s *Service + groupKey string + member *Member + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Add user to the specified group. +func (r *MembersService) Insert(groupKey string, member *Member) *MembersInsertCall { + c := &MembersInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + c.member = member + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *MembersInsertCall) Fields(s ...googleapi.Field) *MembersInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *MembersInsertCall) Context(ctx context.Context) *MembersInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *MembersInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *MembersInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.member) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/members") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.members.insert" call. +// Exactly one of *Member or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Member.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *MembersInsertCall) Do(opts ...googleapi.CallOption) (*Member, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Member{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Add user to the specified group.", + // "httpMethod": "POST", + // "id": "directory.members.insert", + // "parameterOrder": [ + // "groupKey" + // ], + // "parameters": { + // "groupKey": { + // "description": "Email or immutable ID of the group", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}/members", + // "request": { + // "$ref": "Member" + // }, + // "response": { + // "$ref": "Member" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group", + // "https://www.googleapis.com/auth/admin.directory.group.member" + // ] + // } + +} + +// method id "directory.members.list": + +type MembersListCall struct { + s *Service + groupKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieve all members in a group (paginated) +func (r *MembersService) List(groupKey string) *MembersListCall { + c := &MembersListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + return c +} + +// IncludeDerivedMembership sets the optional parameter +// "includeDerivedMembership": Whether to list indirect memberships. +// Default: false. +func (c *MembersListCall) IncludeDerivedMembership(includeDerivedMembership bool) *MembersListCall { + c.urlParams_.Set("includeDerivedMembership", fmt.Sprint(includeDerivedMembership)) + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return. Max allowed value is 200. +func (c *MembersListCall) MaxResults(maxResults int64) *MembersListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// PageToken sets the optional parameter "pageToken": Token to specify +// next page in the list +func (c *MembersListCall) PageToken(pageToken string) *MembersListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Roles sets the optional parameter "roles": Comma separated role +// values to filter list results on. +func (c *MembersListCall) Roles(roles string) *MembersListCall { + c.urlParams_.Set("roles", roles) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *MembersListCall) Fields(s ...googleapi.Field) *MembersListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *MembersListCall) IfNoneMatch(entityTag string) *MembersListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *MembersListCall) Context(ctx context.Context) *MembersListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *MembersListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *MembersListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/members") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.members.list" call. +// Exactly one of *Members or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Members.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *MembersListCall) Do(opts ...googleapi.CallOption) (*Members, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Members{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve all members in a group (paginated)", + // "httpMethod": "GET", + // "id": "directory.members.list", + // "parameterOrder": [ + // "groupKey" + // ], + // "parameters": { + // "groupKey": { + // "description": "Email or immutable ID of the group", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "includeDerivedMembership": { + // "description": "Whether to list indirect memberships. Default: false.", + // "location": "query", + // "type": "boolean" + // }, + // "maxResults": { + // "default": "200", + // "description": "Maximum number of results to return. Max allowed value is 200.", + // "format": "int32", + // "location": "query", + // "minimum": "1", + // "type": "integer" + // }, + // "pageToken": { + // "description": "Token to specify next page in the list", + // "location": "query", + // "type": "string" + // }, + // "roles": { + // "description": "Comma separated role values to filter list results on.", + // "location": "query", + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}/members", + // "response": { + // "$ref": "Members" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group", + // "https://www.googleapis.com/auth/admin.directory.group.member", + // "https://www.googleapis.com/auth/admin.directory.group.member.readonly", + // "https://www.googleapis.com/auth/admin.directory.group.readonly" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *MembersListCall) Pages(ctx context.Context, f func(*Members) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "directory.members.patch": + +type MembersPatchCall struct { + s *Service + groupKey string + memberKey string + member *Member + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Update membership of a user in the specified group. This +// method supports patch semantics. +func (r *MembersService) Patch(groupKey string, memberKey string, member *Member) *MembersPatchCall { + c := &MembersPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + c.memberKey = memberKey + c.member = member + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *MembersPatchCall) Fields(s ...googleapi.Field) *MembersPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *MembersPatchCall) Context(ctx context.Context) *MembersPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *MembersPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *MembersPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.member) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/members/{memberKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + "memberKey": c.memberKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.members.patch" call. +// Exactly one of *Member or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Member.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *MembersPatchCall) Do(opts ...googleapi.CallOption) (*Member, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Member{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Update membership of a user in the specified group. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "directory.members.patch", + // "parameterOrder": [ + // "groupKey", + // "memberKey" + // ], + // "parameters": { + // "groupKey": { + // "description": "Email or immutable ID of the group. If ID, it should match with id of group object", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "memberKey": { + // "description": "Email or immutable ID of the user. If ID, it should match with id of member object", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}/members/{memberKey}", + // "request": { + // "$ref": "Member" + // }, + // "response": { + // "$ref": "Member" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group", + // "https://www.googleapis.com/auth/admin.directory.group.member" + // ] + // } + +} + +// method id "directory.members.update": + +type MembersUpdateCall struct { + s *Service + groupKey string + memberKey string + member *Member + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Update membership of a user in the specified group. +func (r *MembersService) Update(groupKey string, memberKey string, member *Member) *MembersUpdateCall { + c := &MembersUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.groupKey = groupKey + c.memberKey = memberKey + c.member = member + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *MembersUpdateCall) Fields(s ...googleapi.Field) *MembersUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *MembersUpdateCall) Context(ctx context.Context) *MembersUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *MembersUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *MembersUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.member) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/members/{memberKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PUT", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "groupKey": c.groupKey, + "memberKey": c.memberKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.members.update" call. +// Exactly one of *Member or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Member.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *MembersUpdateCall) Do(opts ...googleapi.CallOption) (*Member, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Member{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Update membership of a user in the specified group.", + // "httpMethod": "PUT", + // "id": "directory.members.update", + // "parameterOrder": [ + // "groupKey", + // "memberKey" + // ], + // "parameters": { + // "groupKey": { + // "description": "Email or immutable ID of the group. If ID, it should match with id of group object", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "memberKey": { + // "description": "Email or immutable ID of the user. If ID, it should match with id of member object", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "groups/{groupKey}/members/{memberKey}", + // "request": { + // "$ref": "Member" + // }, + // "response": { + // "$ref": "Member" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.group", + // "https://www.googleapis.com/auth/admin.directory.group.member" + // ] + // } + +} + +// method id "directory.mobiledevices.action": + +type MobiledevicesActionCall struct { + s *Service + customerId string + resourceId string + mobiledeviceaction *MobileDeviceAction + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Action: Take action on Mobile Device +func (r *MobiledevicesService) Action(customerId string, resourceId string, mobiledeviceaction *MobileDeviceAction) *MobiledevicesActionCall { + c := &MobiledevicesActionCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.resourceId = resourceId + c.mobiledeviceaction = mobiledeviceaction + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *MobiledevicesActionCall) Fields(s ...googleapi.Field) *MobiledevicesActionCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *MobiledevicesActionCall) Context(ctx context.Context) *MobiledevicesActionCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *MobiledevicesActionCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *MobiledevicesActionCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.mobiledeviceaction) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/mobile/{resourceId}/action") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "resourceId": c.resourceId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.mobiledevices.action" call. +func (c *MobiledevicesActionCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Take action on Mobile Device", + // "httpMethod": "POST", + // "id": "directory.mobiledevices.action", + // "parameterOrder": [ + // "customerId", + // "resourceId" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "resourceId": { + // "description": "Immutable ID of Mobile Device", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/devices/mobile/{resourceId}/action", + // "request": { + // "$ref": "MobileDeviceAction" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.device.mobile", + // "https://www.googleapis.com/auth/admin.directory.device.mobile.action" + // ] + // } + +} + +// method id "directory.mobiledevices.delete": + +type MobiledevicesDeleteCall struct { + s *Service + customerId string + resourceId string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Delete Mobile Device +func (r *MobiledevicesService) Delete(customerId string, resourceId string) *MobiledevicesDeleteCall { + c := &MobiledevicesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.resourceId = resourceId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *MobiledevicesDeleteCall) Fields(s ...googleapi.Field) *MobiledevicesDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *MobiledevicesDeleteCall) Context(ctx context.Context) *MobiledevicesDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *MobiledevicesDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *MobiledevicesDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/mobile/{resourceId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "resourceId": c.resourceId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.mobiledevices.delete" call. +func (c *MobiledevicesDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Delete Mobile Device", + // "httpMethod": "DELETE", + // "id": "directory.mobiledevices.delete", + // "parameterOrder": [ + // "customerId", + // "resourceId" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "resourceId": { + // "description": "Immutable ID of Mobile Device", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/devices/mobile/{resourceId}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.device.mobile" + // ] + // } + +} + +// method id "directory.mobiledevices.get": + +type MobiledevicesGetCall struct { + s *Service + customerId string + resourceId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieve Mobile Device +func (r *MobiledevicesService) Get(customerId string, resourceId string) *MobiledevicesGetCall { + c := &MobiledevicesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.resourceId = resourceId + return c +} + +// Projection sets the optional parameter "projection": Restrict +// information returned to a set of selected fields. +// +// Possible values: +// "BASIC" - Includes only the basic metadata fields (e.g., deviceId, +// model, status, type, and status) +// "FULL" - Includes all metadata fields +func (c *MobiledevicesGetCall) Projection(projection string) *MobiledevicesGetCall { + c.urlParams_.Set("projection", projection) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *MobiledevicesGetCall) Fields(s ...googleapi.Field) *MobiledevicesGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *MobiledevicesGetCall) IfNoneMatch(entityTag string) *MobiledevicesGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *MobiledevicesGetCall) Context(ctx context.Context) *MobiledevicesGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *MobiledevicesGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *MobiledevicesGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/mobile/{resourceId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "resourceId": c.resourceId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.mobiledevices.get" call. +// Exactly one of *MobileDevice or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *MobileDevice.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *MobiledevicesGetCall) Do(opts ...googleapi.CallOption) (*MobileDevice, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &MobileDevice{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve Mobile Device", + // "httpMethod": "GET", + // "id": "directory.mobiledevices.get", + // "parameterOrder": [ + // "customerId", + // "resourceId" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projection": { + // "description": "Restrict information returned to a set of selected fields.", + // "enum": [ + // "BASIC", + // "FULL" + // ], + // "enumDescriptions": [ + // "Includes only the basic metadata fields (e.g., deviceId, model, status, type, and status)", + // "Includes all metadata fields" + // ], + // "location": "query", + // "type": "string" + // }, + // "resourceId": { + // "description": "Immutable ID of Mobile Device", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/devices/mobile/{resourceId}", + // "response": { + // "$ref": "MobileDevice" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.device.mobile", + // "https://www.googleapis.com/auth/admin.directory.device.mobile.action", + // "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly" + // ] + // } + +} + +// method id "directory.mobiledevices.list": + +type MobiledevicesListCall struct { + s *Service + customerId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieve all Mobile Devices of a customer (paginated) +func (r *MobiledevicesService) List(customerId string) *MobiledevicesListCall { + c := &MobiledevicesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return. Max allowed value is 100. +func (c *MobiledevicesListCall) MaxResults(maxResults int64) *MobiledevicesListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// OrderBy sets the optional parameter "orderBy": Column to use for +// sorting results +// +// Possible values: +// "deviceId" - Mobile Device serial number. +// "email" - Owner user email. +// "lastSync" - Last policy settings sync date time of the device. +// "model" - Mobile Device model. +// "name" - Owner user name. +// "os" - Mobile operating system. +// "status" - Status of the device. +// "type" - Type of the device. +func (c *MobiledevicesListCall) OrderBy(orderBy string) *MobiledevicesListCall { + c.urlParams_.Set("orderBy", orderBy) + return c +} + +// PageToken sets the optional parameter "pageToken": Token to specify +// next page in the list +func (c *MobiledevicesListCall) PageToken(pageToken string) *MobiledevicesListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Projection sets the optional parameter "projection": Restrict +// information returned to a set of selected fields. +// +// Possible values: +// "BASIC" - Includes only the basic metadata fields (e.g., deviceId, +// model, status, type, and status) +// "FULL" - Includes all metadata fields +func (c *MobiledevicesListCall) Projection(projection string) *MobiledevicesListCall { + c.urlParams_.Set("projection", projection) + return c +} + +// Query sets the optional parameter "query": Search string in the +// format given at +// http://support.google.com/a/bin/answer.py?answer=1408863#search +func (c *MobiledevicesListCall) Query(query string) *MobiledevicesListCall { + c.urlParams_.Set("query", query) + return c +} + +// SortOrder sets the optional parameter "sortOrder": Whether to return +// results in ascending or descending order. Only of use when orderBy is +// also used +// +// Possible values: +// "ASCENDING" - Ascending order. +// "DESCENDING" - Descending order. +func (c *MobiledevicesListCall) SortOrder(sortOrder string) *MobiledevicesListCall { + c.urlParams_.Set("sortOrder", sortOrder) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *MobiledevicesListCall) Fields(s ...googleapi.Field) *MobiledevicesListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *MobiledevicesListCall) IfNoneMatch(entityTag string) *MobiledevicesListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *MobiledevicesListCall) Context(ctx context.Context) *MobiledevicesListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *MobiledevicesListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *MobiledevicesListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/mobile") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.mobiledevices.list" call. +// Exactly one of *MobileDevices or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *MobileDevices.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *MobiledevicesListCall) Do(opts ...googleapi.CallOption) (*MobileDevices, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &MobileDevices{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve all Mobile Devices of a customer (paginated)", + // "httpMethod": "GET", + // "id": "directory.mobiledevices.list", + // "parameterOrder": [ + // "customerId" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "maxResults": { + // "default": "100", + // "description": "Maximum number of results to return. Max allowed value is 100.", + // "format": "int32", + // "location": "query", + // "minimum": "1", + // "type": "integer" + // }, + // "orderBy": { + // "description": "Column to use for sorting results", + // "enum": [ + // "deviceId", + // "email", + // "lastSync", + // "model", + // "name", + // "os", + // "status", + // "type" + // ], + // "enumDescriptions": [ + // "Mobile Device serial number.", + // "Owner user email.", + // "Last policy settings sync date time of the device.", + // "Mobile Device model.", + // "Owner user name.", + // "Mobile operating system.", + // "Status of the device.", + // "Type of the device." + // ], + // "location": "query", + // "type": "string" + // }, + // "pageToken": { + // "description": "Token to specify next page in the list", + // "location": "query", + // "type": "string" + // }, + // "projection": { + // "description": "Restrict information returned to a set of selected fields.", + // "enum": [ + // "BASIC", + // "FULL" + // ], + // "enumDescriptions": [ + // "Includes only the basic metadata fields (e.g., deviceId, model, status, type, and status)", + // "Includes all metadata fields" + // ], + // "location": "query", + // "type": "string" + // }, + // "query": { + // "description": "Search string in the format given at http://support.google.com/a/bin/answer.py?answer=1408863#search", + // "location": "query", + // "type": "string" + // }, + // "sortOrder": { + // "description": "Whether to return results in ascending or descending order. Only of use when orderBy is also used", + // "enum": [ + // "ASCENDING", + // "DESCENDING" + // ], + // "enumDescriptions": [ + // "Ascending order.", + // "Descending order." + // ], + // "location": "query", + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/devices/mobile", + // "response": { + // "$ref": "MobileDevices" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.device.mobile", + // "https://www.googleapis.com/auth/admin.directory.device.mobile.action", + // "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *MobiledevicesListCall) Pages(ctx context.Context, f func(*MobileDevices) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "directory.notifications.delete": + +type NotificationsDeleteCall struct { + s *Service + customer string + notificationId string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes a notification +func (r *NotificationsService) Delete(customer string, notificationId string) *NotificationsDeleteCall { + c := &NotificationsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.notificationId = notificationId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *NotificationsDeleteCall) Fields(s ...googleapi.Field) *NotificationsDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *NotificationsDeleteCall) Context(ctx context.Context) *NotificationsDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *NotificationsDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *NotificationsDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/notifications/{notificationId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "notificationId": c.notificationId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.notifications.delete" call. +func (c *NotificationsDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Deletes a notification", + // "httpMethod": "DELETE", + // "id": "directory.notifications.delete", + // "parameterOrder": [ + // "customer", + // "notificationId" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account. The customerId is also returned as part of the Users resource.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "notificationId": { + // "description": "The unique ID of the notification.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/notifications/{notificationId}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.notifications" + // ] + // } + +} + +// method id "directory.notifications.get": + +type NotificationsGetCall struct { + s *Service + customer string + notificationId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieves a notification. +func (r *NotificationsService) Get(customer string, notificationId string) *NotificationsGetCall { + c := &NotificationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.notificationId = notificationId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *NotificationsGetCall) Fields(s ...googleapi.Field) *NotificationsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *NotificationsGetCall) IfNoneMatch(entityTag string) *NotificationsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *NotificationsGetCall) Context(ctx context.Context) *NotificationsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *NotificationsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *NotificationsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/notifications/{notificationId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "notificationId": c.notificationId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.notifications.get" call. +// Exactly one of *Notification or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *Notification.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *NotificationsGetCall) Do(opts ...googleapi.CallOption) (*Notification, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Notification{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a notification.", + // "httpMethod": "GET", + // "id": "directory.notifications.get", + // "parameterOrder": [ + // "customer", + // "notificationId" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account. The customerId is also returned as part of the Users resource.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "notificationId": { + // "description": "The unique ID of the notification.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/notifications/{notificationId}", + // "response": { + // "$ref": "Notification" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.notifications" + // ] + // } + +} + +// method id "directory.notifications.list": + +type NotificationsListCall struct { + s *Service + customer string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieves a list of notifications. +func (r *NotificationsService) List(customer string) *NotificationsListCall { + c := &NotificationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + return c +} + +// Language sets the optional parameter "language": The ISO 639-1 code +// of the language notifications are returned in. The default is English +// (en). +func (c *NotificationsListCall) Language(language string) *NotificationsListCall { + c.urlParams_.Set("language", language) + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of notifications to return per page. The default is 100. +func (c *NotificationsListCall) MaxResults(maxResults int64) *NotificationsListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// PageToken sets the optional parameter "pageToken": The token to +// specify the page of results to retrieve. +func (c *NotificationsListCall) PageToken(pageToken string) *NotificationsListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *NotificationsListCall) Fields(s ...googleapi.Field) *NotificationsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *NotificationsListCall) IfNoneMatch(entityTag string) *NotificationsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *NotificationsListCall) Context(ctx context.Context) *NotificationsListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *NotificationsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *NotificationsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/notifications") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.notifications.list" call. +// Exactly one of *Notifications or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *Notifications.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *NotificationsListCall) Do(opts ...googleapi.CallOption) (*Notifications, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Notifications{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a list of notifications.", + // "httpMethod": "GET", + // "id": "directory.notifications.list", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "language": { + // "description": "The ISO 639-1 code of the language notifications are returned in. The default is English (en).", + // "location": "query", + // "type": "string" + // }, + // "maxResults": { + // "description": "Maximum number of notifications to return per page. The default is 100.", + // "format": "uint32", + // "location": "query", + // "type": "integer" + // }, + // "pageToken": { + // "description": "The token to specify the page of results to retrieve.", + // "location": "query", + // "type": "string" + // } + // }, + // "path": "customer/{customer}/notifications", + // "response": { + // "$ref": "Notifications" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.notifications" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *NotificationsListCall) Pages(ctx context.Context, f func(*Notifications) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "directory.notifications.patch": + +type NotificationsPatchCall struct { + s *Service + customer string + notificationId string + notification *Notification + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates a notification. This method supports patch semantics. +func (r *NotificationsService) Patch(customer string, notificationId string, notification *Notification) *NotificationsPatchCall { + c := &NotificationsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.notificationId = notificationId + c.notification = notification + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *NotificationsPatchCall) Fields(s ...googleapi.Field) *NotificationsPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *NotificationsPatchCall) Context(ctx context.Context) *NotificationsPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *NotificationsPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *NotificationsPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.notification) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/notifications/{notificationId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "notificationId": c.notificationId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.notifications.patch" call. +// Exactly one of *Notification or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *Notification.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *NotificationsPatchCall) Do(opts ...googleapi.CallOption) (*Notification, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Notification{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates a notification. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "directory.notifications.patch", + // "parameterOrder": [ + // "customer", + // "notificationId" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "notificationId": { + // "description": "The unique ID of the notification.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/notifications/{notificationId}", + // "request": { + // "$ref": "Notification" + // }, + // "response": { + // "$ref": "Notification" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.notifications" + // ] + // } + +} + +// method id "directory.notifications.update": + +type NotificationsUpdateCall struct { + s *Service + customer string + notificationId string + notification *Notification + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Updates a notification. +func (r *NotificationsService) Update(customer string, notificationId string, notification *Notification) *NotificationsUpdateCall { + c := &NotificationsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.notificationId = notificationId + c.notification = notification + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *NotificationsUpdateCall) Fields(s ...googleapi.Field) *NotificationsUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *NotificationsUpdateCall) Context(ctx context.Context) *NotificationsUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *NotificationsUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *NotificationsUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.notification) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/notifications/{notificationId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PUT", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "notificationId": c.notificationId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.notifications.update" call. +// Exactly one of *Notification or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *Notification.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *NotificationsUpdateCall) Do(opts ...googleapi.CallOption) (*Notification, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Notification{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates a notification.", + // "httpMethod": "PUT", + // "id": "directory.notifications.update", + // "parameterOrder": [ + // "customer", + // "notificationId" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "notificationId": { + // "description": "The unique ID of the notification.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/notifications/{notificationId}", + // "request": { + // "$ref": "Notification" + // }, + // "response": { + // "$ref": "Notification" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.notifications" + // ] + // } + +} + +// method id "directory.orgunits.delete": + +type OrgunitsDeleteCall struct { + s *Service + customerId string + orgUnitPath []string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Remove organizational unit +func (r *OrgunitsService) Delete(customerId string, orgUnitPath []string) *OrgunitsDeleteCall { + c := &OrgunitsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.orgUnitPath = append([]string{}, orgUnitPath...) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *OrgunitsDeleteCall) Fields(s ...googleapi.Field) *OrgunitsDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *OrgunitsDeleteCall) Context(ctx context.Context) *OrgunitsDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *OrgunitsDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *OrgunitsDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/orgunits{/orgUnitPath*}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "orgUnitPath": c.orgUnitPath[0], + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.orgunits.delete" call. +func (c *OrgunitsDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Remove organizational unit", + // "httpMethod": "DELETE", + // "id": "directory.orgunits.delete", + // "parameterOrder": [ + // "customerId", + // "orgUnitPath" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "orgUnitPath": { + // "description": "Full path of the organizational unit or its ID", + // "location": "path", + // "repeated": true, + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/orgunits{/orgUnitPath*}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.orgunit" + // ] + // } + +} + +// method id "directory.orgunits.get": + +type OrgunitsGetCall struct { + s *Service + customerId string + orgUnitPath []string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieve organizational unit +func (r *OrgunitsService) Get(customerId string, orgUnitPath []string) *OrgunitsGetCall { + c := &OrgunitsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.orgUnitPath = append([]string{}, orgUnitPath...) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *OrgunitsGetCall) Fields(s ...googleapi.Field) *OrgunitsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *OrgunitsGetCall) IfNoneMatch(entityTag string) *OrgunitsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *OrgunitsGetCall) Context(ctx context.Context) *OrgunitsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *OrgunitsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *OrgunitsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/orgunits{/orgUnitPath*}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "orgUnitPath": c.orgUnitPath[0], + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.orgunits.get" call. +// Exactly one of *OrgUnit or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *OrgUnit.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *OrgunitsGetCall) Do(opts ...googleapi.CallOption) (*OrgUnit, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &OrgUnit{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve organizational unit", + // "httpMethod": "GET", + // "id": "directory.orgunits.get", + // "parameterOrder": [ + // "customerId", + // "orgUnitPath" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "orgUnitPath": { + // "description": "Full path of the organizational unit or its ID", + // "location": "path", + // "repeated": true, + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/orgunits{/orgUnitPath*}", + // "response": { + // "$ref": "OrgUnit" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.orgunit", + // "https://www.googleapis.com/auth/admin.directory.orgunit.readonly" + // ] + // } + +} + +// method id "directory.orgunits.insert": + +type OrgunitsInsertCall struct { + s *Service + customerId string + orgunit *OrgUnit + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Add organizational unit +func (r *OrgunitsService) Insert(customerId string, orgunit *OrgUnit) *OrgunitsInsertCall { + c := &OrgunitsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.orgunit = orgunit + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *OrgunitsInsertCall) Fields(s ...googleapi.Field) *OrgunitsInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *OrgunitsInsertCall) Context(ctx context.Context) *OrgunitsInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *OrgunitsInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *OrgunitsInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.orgunit) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/orgunits") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.orgunits.insert" call. +// Exactly one of *OrgUnit or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *OrgUnit.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *OrgunitsInsertCall) Do(opts ...googleapi.CallOption) (*OrgUnit, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &OrgUnit{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Add organizational unit", + // "httpMethod": "POST", + // "id": "directory.orgunits.insert", + // "parameterOrder": [ + // "customerId" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/orgunits", + // "request": { + // "$ref": "OrgUnit" + // }, + // "response": { + // "$ref": "OrgUnit" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.orgunit" + // ] + // } + +} + +// method id "directory.orgunits.list": + +type OrgunitsListCall struct { + s *Service + customerId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieve all organizational units +func (r *OrgunitsService) List(customerId string) *OrgunitsListCall { + c := &OrgunitsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + return c +} + +// OrgUnitPath sets the optional parameter "orgUnitPath": the +// URL-encoded organizational unit's path or its ID +func (c *OrgunitsListCall) OrgUnitPath(orgUnitPath string) *OrgunitsListCall { + c.urlParams_.Set("orgUnitPath", orgUnitPath) + return c +} + +// Type sets the optional parameter "type": Whether to return all +// sub-organizations or just immediate children +// +// Possible values: +// "all" - All sub-organizational units. +// "children" - Immediate children only (default). +func (c *OrgunitsListCall) Type(type_ string) *OrgunitsListCall { + c.urlParams_.Set("type", type_) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *OrgunitsListCall) Fields(s ...googleapi.Field) *OrgunitsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *OrgunitsListCall) IfNoneMatch(entityTag string) *OrgunitsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *OrgunitsListCall) Context(ctx context.Context) *OrgunitsListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *OrgunitsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *OrgunitsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/orgunits") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.orgunits.list" call. +// Exactly one of *OrgUnits or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *OrgUnits.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *OrgunitsListCall) Do(opts ...googleapi.CallOption) (*OrgUnits, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &OrgUnits{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve all organizational units", + // "httpMethod": "GET", + // "id": "directory.orgunits.list", + // "parameterOrder": [ + // "customerId" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "orgUnitPath": { + // "default": "", + // "description": "the URL-encoded organizational unit's path or its ID", + // "location": "query", + // "type": "string" + // }, + // "type": { + // "description": "Whether to return all sub-organizations or just immediate children", + // "enum": [ + // "all", + // "children" + // ], + // "enumDescriptions": [ + // "All sub-organizational units.", + // "Immediate children only (default)." + // ], + // "location": "query", + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/orgunits", + // "response": { + // "$ref": "OrgUnits" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.orgunit", + // "https://www.googleapis.com/auth/admin.directory.orgunit.readonly" + // ] + // } + +} + +// method id "directory.orgunits.patch": + +type OrgunitsPatchCall struct { + s *Service + customerId string + orgUnitPath []string + orgunit *OrgUnit + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Update organizational unit. This method supports patch +// semantics. +func (r *OrgunitsService) Patch(customerId string, orgUnitPath []string, orgunit *OrgUnit) *OrgunitsPatchCall { + c := &OrgunitsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.orgUnitPath = append([]string{}, orgUnitPath...) + c.orgunit = orgunit + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *OrgunitsPatchCall) Fields(s ...googleapi.Field) *OrgunitsPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *OrgunitsPatchCall) Context(ctx context.Context) *OrgunitsPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *OrgunitsPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *OrgunitsPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.orgunit) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/orgunits{/orgUnitPath*}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "orgUnitPath": c.orgUnitPath[0], + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.orgunits.patch" call. +// Exactly one of *OrgUnit or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *OrgUnit.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *OrgunitsPatchCall) Do(opts ...googleapi.CallOption) (*OrgUnit, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &OrgUnit{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Update organizational unit. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "directory.orgunits.patch", + // "parameterOrder": [ + // "customerId", + // "orgUnitPath" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "orgUnitPath": { + // "description": "Full path of the organizational unit or its ID", + // "location": "path", + // "repeated": true, + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/orgunits{/orgUnitPath*}", + // "request": { + // "$ref": "OrgUnit" + // }, + // "response": { + // "$ref": "OrgUnit" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.orgunit" + // ] + // } + +} + +// method id "directory.orgunits.update": + +type OrgunitsUpdateCall struct { + s *Service + customerId string + orgUnitPath []string + orgunit *OrgUnit + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Update organizational unit +func (r *OrgunitsService) Update(customerId string, orgUnitPath []string, orgunit *OrgUnit) *OrgunitsUpdateCall { + c := &OrgunitsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.orgUnitPath = append([]string{}, orgUnitPath...) + c.orgunit = orgunit + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *OrgunitsUpdateCall) Fields(s ...googleapi.Field) *OrgunitsUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *OrgunitsUpdateCall) Context(ctx context.Context) *OrgunitsUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *OrgunitsUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *OrgunitsUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.orgunit) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/orgunits{/orgUnitPath*}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PUT", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "orgUnitPath": c.orgUnitPath[0], + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.orgunits.update" call. +// Exactly one of *OrgUnit or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *OrgUnit.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *OrgunitsUpdateCall) Do(opts ...googleapi.CallOption) (*OrgUnit, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &OrgUnit{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Update organizational unit", + // "httpMethod": "PUT", + // "id": "directory.orgunits.update", + // "parameterOrder": [ + // "customerId", + // "orgUnitPath" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "orgUnitPath": { + // "description": "Full path of the organizational unit or its ID", + // "location": "path", + // "repeated": true, + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/orgunits{/orgUnitPath*}", + // "request": { + // "$ref": "OrgUnit" + // }, + // "response": { + // "$ref": "OrgUnit" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.orgunit" + // ] + // } + +} + +// method id "directory.privileges.list": + +type PrivilegesListCall struct { + s *Service + customer string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieves a paginated list of all privileges for a customer. +func (r *PrivilegesService) List(customer string) *PrivilegesListCall { + c := &PrivilegesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *PrivilegesListCall) Fields(s ...googleapi.Field) *PrivilegesListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *PrivilegesListCall) IfNoneMatch(entityTag string) *PrivilegesListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *PrivilegesListCall) Context(ctx context.Context) *PrivilegesListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *PrivilegesListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *PrivilegesListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles/ALL/privileges") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.privileges.list" call. +// Exactly one of *Privileges or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *Privileges.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *PrivilegesListCall) Do(opts ...googleapi.CallOption) (*Privileges, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Privileges{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a paginated list of all privileges for a customer.", + // "httpMethod": "GET", + // "id": "directory.privileges.list", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/roles/ALL/privileges", + // "response": { + // "$ref": "Privileges" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.rolemanagement", + // "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" + // ] + // } + +} + +// method id "directory.resolvedAppAccessSettings.GetSettings": + +type ResolvedAppAccessSettingsGetSettingsCall struct { + s *Service + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// GetSettings: Retrieves resolved app access settings of the logged in +// user. +func (r *ResolvedAppAccessSettingsService) GetSettings() *ResolvedAppAccessSettingsGetSettingsCall { + c := &ResolvedAppAccessSettingsGetSettingsCall{s: r.s, urlParams_: make(gensupport.URLParams)} + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResolvedAppAccessSettingsGetSettingsCall) Fields(s ...googleapi.Field) *ResolvedAppAccessSettingsGetSettingsCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *ResolvedAppAccessSettingsGetSettingsCall) IfNoneMatch(entityTag string) *ResolvedAppAccessSettingsGetSettingsCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResolvedAppAccessSettingsGetSettingsCall) Context(ctx context.Context) *ResolvedAppAccessSettingsGetSettingsCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResolvedAppAccessSettingsGetSettingsCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResolvedAppAccessSettingsGetSettingsCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "resolvedappaccesssettings") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resolvedAppAccessSettings.GetSettings" call. +// Exactly one of *AppAccessCollections or error will be non-nil. Any +// non-2xx status code is an error. Response headers are in either +// *AppAccessCollections.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *ResolvedAppAccessSettingsGetSettingsCall) Do(opts ...googleapi.CallOption) (*AppAccessCollections, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &AppAccessCollections{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves resolved app access settings of the logged in user.", + // "httpMethod": "GET", + // "id": "directory.resolvedAppAccessSettings.GetSettings", + // "path": "resolvedappaccesssettings", + // "response": { + // "$ref": "AppAccessCollections" + // } + // } + +} + +// method id "directory.resolvedAppAccessSettings.ListTrustedApps": + +type ResolvedAppAccessSettingsListTrustedAppsCall struct { + s *Service + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// ListTrustedApps: Retrieves the list of apps trusted by the admin of +// the logged in user. +func (r *ResolvedAppAccessSettingsService) ListTrustedApps() *ResolvedAppAccessSettingsListTrustedAppsCall { + c := &ResolvedAppAccessSettingsListTrustedAppsCall{s: r.s, urlParams_: make(gensupport.URLParams)} + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResolvedAppAccessSettingsListTrustedAppsCall) Fields(s ...googleapi.Field) *ResolvedAppAccessSettingsListTrustedAppsCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *ResolvedAppAccessSettingsListTrustedAppsCall) IfNoneMatch(entityTag string) *ResolvedAppAccessSettingsListTrustedAppsCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResolvedAppAccessSettingsListTrustedAppsCall) Context(ctx context.Context) *ResolvedAppAccessSettingsListTrustedAppsCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResolvedAppAccessSettingsListTrustedAppsCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResolvedAppAccessSettingsListTrustedAppsCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "trustedapps") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resolvedAppAccessSettings.ListTrustedApps" call. +// Exactly one of *TrustedApps or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *TrustedApps.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ResolvedAppAccessSettingsListTrustedAppsCall) Do(opts ...googleapi.CallOption) (*TrustedApps, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &TrustedApps{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves the list of apps trusted by the admin of the logged in user.", + // "httpMethod": "GET", + // "id": "directory.resolvedAppAccessSettings.ListTrustedApps", + // "path": "trustedapps", + // "response": { + // "$ref": "TrustedApps" + // } + // } + +} + +// method id "directory.resources.buildings.delete": + +type ResourcesBuildingsDeleteCall struct { + s *Service + customer string + buildingId string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes a building. +func (r *ResourcesBuildingsService) Delete(customer string, buildingId string) *ResourcesBuildingsDeleteCall { + c := &ResourcesBuildingsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.buildingId = buildingId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesBuildingsDeleteCall) Fields(s ...googleapi.Field) *ResourcesBuildingsDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesBuildingsDeleteCall) Context(ctx context.Context) *ResourcesBuildingsDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesBuildingsDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesBuildingsDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/buildings/{buildingId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "buildingId": c.buildingId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.buildings.delete" call. +func (c *ResourcesBuildingsDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Deletes a building.", + // "httpMethod": "DELETE", + // "id": "directory.resources.buildings.delete", + // "parameterOrder": [ + // "customer", + // "buildingId" + // ], + // "parameters": { + // "buildingId": { + // "description": "The ID of the building to delete.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/buildings/{buildingId}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar" + // ] + // } + +} + +// method id "directory.resources.buildings.get": + +type ResourcesBuildingsGetCall struct { + s *Service + customer string + buildingId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieves a building. +func (r *ResourcesBuildingsService) Get(customer string, buildingId string) *ResourcesBuildingsGetCall { + c := &ResourcesBuildingsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.buildingId = buildingId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesBuildingsGetCall) Fields(s ...googleapi.Field) *ResourcesBuildingsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *ResourcesBuildingsGetCall) IfNoneMatch(entityTag string) *ResourcesBuildingsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesBuildingsGetCall) Context(ctx context.Context) *ResourcesBuildingsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesBuildingsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesBuildingsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/buildings/{buildingId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "buildingId": c.buildingId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.buildings.get" call. +// Exactly one of *Building or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Building.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ResourcesBuildingsGetCall) Do(opts ...googleapi.CallOption) (*Building, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Building{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a building.", + // "httpMethod": "GET", + // "id": "directory.resources.buildings.get", + // "parameterOrder": [ + // "customer", + // "buildingId" + // ], + // "parameters": { + // "buildingId": { + // "description": "The unique ID of the building to retrieve.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/buildings/{buildingId}", + // "response": { + // "$ref": "Building" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar", + // "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" + // ] + // } + +} + +// method id "directory.resources.buildings.insert": + +type ResourcesBuildingsInsertCall struct { + s *Service + customer string + building *Building + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Inserts a building. +func (r *ResourcesBuildingsService) Insert(customer string, building *Building) *ResourcesBuildingsInsertCall { + c := &ResourcesBuildingsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.building = building + return c +} + +// CoordinatesSource sets the optional parameter "coordinatesSource": +// Source from which Building.coordinates are derived. +// +// Possible values: +// "CLIENT_SPECIFIED" - Building.coordinates are set to the +// coordinates included in the request. +// "RESOLVED_FROM_ADDRESS" - Building.coordinates are automatically +// populated based on the postal address. +// "SOURCE_UNSPECIFIED" (default) - Defaults to RESOLVED_FROM_ADDRESS +// if postal address is provided. Otherwise, defaults to +// CLIENT_SPECIFIED if coordinates are provided. +func (c *ResourcesBuildingsInsertCall) CoordinatesSource(coordinatesSource string) *ResourcesBuildingsInsertCall { + c.urlParams_.Set("coordinatesSource", coordinatesSource) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesBuildingsInsertCall) Fields(s ...googleapi.Field) *ResourcesBuildingsInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesBuildingsInsertCall) Context(ctx context.Context) *ResourcesBuildingsInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesBuildingsInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesBuildingsInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.building) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/buildings") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.buildings.insert" call. +// Exactly one of *Building or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Building.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ResourcesBuildingsInsertCall) Do(opts ...googleapi.CallOption) (*Building, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Building{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Inserts a building.", + // "httpMethod": "POST", + // "id": "directory.resources.buildings.insert", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "coordinatesSource": { + // "default": "SOURCE_UNSPECIFIED", + // "description": "Source from which Building.coordinates are derived.", + // "enum": [ + // "CLIENT_SPECIFIED", + // "RESOLVED_FROM_ADDRESS", + // "SOURCE_UNSPECIFIED" + // ], + // "enumDescriptions": [ + // "Building.coordinates are set to the coordinates included in the request.", + // "Building.coordinates are automatically populated based on the postal address.", + // "Defaults to RESOLVED_FROM_ADDRESS if postal address is provided. Otherwise, defaults to CLIENT_SPECIFIED if coordinates are provided." + // ], + // "location": "query", + // "type": "string" + // }, + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/buildings", + // "request": { + // "$ref": "Building" + // }, + // "response": { + // "$ref": "Building" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar" + // ] + // } + +} + +// method id "directory.resources.buildings.list": + +type ResourcesBuildingsListCall struct { + s *Service + customer string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieves a list of buildings for an account. +func (r *ResourcesBuildingsService) List(customer string) *ResourcesBuildingsListCall { + c := &ResourcesBuildingsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return. +func (c *ResourcesBuildingsListCall) MaxResults(maxResults int64) *ResourcesBuildingsListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// PageToken sets the optional parameter "pageToken": Token to specify +// the next page in the list. +func (c *ResourcesBuildingsListCall) PageToken(pageToken string) *ResourcesBuildingsListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesBuildingsListCall) Fields(s ...googleapi.Field) *ResourcesBuildingsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *ResourcesBuildingsListCall) IfNoneMatch(entityTag string) *ResourcesBuildingsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesBuildingsListCall) Context(ctx context.Context) *ResourcesBuildingsListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesBuildingsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesBuildingsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/buildings") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.buildings.list" call. +// Exactly one of *Buildings or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *Buildings.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ResourcesBuildingsListCall) Do(opts ...googleapi.CallOption) (*Buildings, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Buildings{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a list of buildings for an account.", + // "httpMethod": "GET", + // "id": "directory.resources.buildings.list", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "maxResults": { + // "description": "Maximum number of results to return.", + // "format": "int32", + // "location": "query", + // "maximum": "500", + // "minimum": "1", + // "type": "integer" + // }, + // "pageToken": { + // "description": "Token to specify the next page in the list.", + // "location": "query", + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/buildings", + // "response": { + // "$ref": "Buildings" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar", + // "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *ResourcesBuildingsListCall) Pages(ctx context.Context, f func(*Buildings) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "directory.resources.buildings.patch": + +type ResourcesBuildingsPatchCall struct { + s *Service + customer string + buildingId string + building *Building + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates a building. This method supports patch semantics. +func (r *ResourcesBuildingsService) Patch(customer string, buildingId string, building *Building) *ResourcesBuildingsPatchCall { + c := &ResourcesBuildingsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.buildingId = buildingId + c.building = building + return c +} + +// CoordinatesSource sets the optional parameter "coordinatesSource": +// Source from which Building.coordinates are derived. +// +// Possible values: +// "CLIENT_SPECIFIED" - Building.coordinates are set to the +// coordinates included in the request. +// "RESOLVED_FROM_ADDRESS" - Building.coordinates are automatically +// populated based on the postal address. +// "SOURCE_UNSPECIFIED" (default) - Defaults to RESOLVED_FROM_ADDRESS +// if postal address is provided. Otherwise, defaults to +// CLIENT_SPECIFIED if coordinates are provided. +func (c *ResourcesBuildingsPatchCall) CoordinatesSource(coordinatesSource string) *ResourcesBuildingsPatchCall { + c.urlParams_.Set("coordinatesSource", coordinatesSource) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesBuildingsPatchCall) Fields(s ...googleapi.Field) *ResourcesBuildingsPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesBuildingsPatchCall) Context(ctx context.Context) *ResourcesBuildingsPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesBuildingsPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesBuildingsPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.building) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/buildings/{buildingId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "buildingId": c.buildingId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.buildings.patch" call. +// Exactly one of *Building or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Building.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ResourcesBuildingsPatchCall) Do(opts ...googleapi.CallOption) (*Building, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Building{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates a building. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "directory.resources.buildings.patch", + // "parameterOrder": [ + // "customer", + // "buildingId" + // ], + // "parameters": { + // "buildingId": { + // "description": "The ID of the building to update.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "coordinatesSource": { + // "default": "SOURCE_UNSPECIFIED", + // "description": "Source from which Building.coordinates are derived.", + // "enum": [ + // "CLIENT_SPECIFIED", + // "RESOLVED_FROM_ADDRESS", + // "SOURCE_UNSPECIFIED" + // ], + // "enumDescriptions": [ + // "Building.coordinates are set to the coordinates included in the request.", + // "Building.coordinates are automatically populated based on the postal address.", + // "Defaults to RESOLVED_FROM_ADDRESS if postal address is provided. Otherwise, defaults to CLIENT_SPECIFIED if coordinates are provided." + // ], + // "location": "query", + // "type": "string" + // }, + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/buildings/{buildingId}", + // "request": { + // "$ref": "Building" + // }, + // "response": { + // "$ref": "Building" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar" + // ] + // } + +} + +// method id "directory.resources.buildings.update": + +type ResourcesBuildingsUpdateCall struct { + s *Service + customer string + buildingId string + building *Building + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Updates a building. +func (r *ResourcesBuildingsService) Update(customer string, buildingId string, building *Building) *ResourcesBuildingsUpdateCall { + c := &ResourcesBuildingsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.buildingId = buildingId + c.building = building + return c +} + +// CoordinatesSource sets the optional parameter "coordinatesSource": +// Source from which Building.coordinates are derived. +// +// Possible values: +// "CLIENT_SPECIFIED" - Building.coordinates are set to the +// coordinates included in the request. +// "RESOLVED_FROM_ADDRESS" - Building.coordinates are automatically +// populated based on the postal address. +// "SOURCE_UNSPECIFIED" (default) - Defaults to RESOLVED_FROM_ADDRESS +// if postal address is provided. Otherwise, defaults to +// CLIENT_SPECIFIED if coordinates are provided. +func (c *ResourcesBuildingsUpdateCall) CoordinatesSource(coordinatesSource string) *ResourcesBuildingsUpdateCall { + c.urlParams_.Set("coordinatesSource", coordinatesSource) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesBuildingsUpdateCall) Fields(s ...googleapi.Field) *ResourcesBuildingsUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesBuildingsUpdateCall) Context(ctx context.Context) *ResourcesBuildingsUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesBuildingsUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesBuildingsUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.building) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/buildings/{buildingId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PUT", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "buildingId": c.buildingId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.buildings.update" call. +// Exactly one of *Building or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Building.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ResourcesBuildingsUpdateCall) Do(opts ...googleapi.CallOption) (*Building, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Building{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates a building.", + // "httpMethod": "PUT", + // "id": "directory.resources.buildings.update", + // "parameterOrder": [ + // "customer", + // "buildingId" + // ], + // "parameters": { + // "buildingId": { + // "description": "The ID of the building to update.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "coordinatesSource": { + // "default": "SOURCE_UNSPECIFIED", + // "description": "Source from which Building.coordinates are derived.", + // "enum": [ + // "CLIENT_SPECIFIED", + // "RESOLVED_FROM_ADDRESS", + // "SOURCE_UNSPECIFIED" + // ], + // "enumDescriptions": [ + // "Building.coordinates are set to the coordinates included in the request.", + // "Building.coordinates are automatically populated based on the postal address.", + // "Defaults to RESOLVED_FROM_ADDRESS if postal address is provided. Otherwise, defaults to CLIENT_SPECIFIED if coordinates are provided." + // ], + // "location": "query", + // "type": "string" + // }, + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/buildings/{buildingId}", + // "request": { + // "$ref": "Building" + // }, + // "response": { + // "$ref": "Building" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar" + // ] + // } + +} + +// method id "directory.resources.calendars.delete": + +type ResourcesCalendarsDeleteCall struct { + s *Service + customer string + calendarResourceId string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes a calendar resource. +func (r *ResourcesCalendarsService) Delete(customer string, calendarResourceId string) *ResourcesCalendarsDeleteCall { + c := &ResourcesCalendarsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.calendarResourceId = calendarResourceId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesCalendarsDeleteCall) Fields(s ...googleapi.Field) *ResourcesCalendarsDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesCalendarsDeleteCall) Context(ctx context.Context) *ResourcesCalendarsDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesCalendarsDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesCalendarsDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/calendars/{calendarResourceId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "calendarResourceId": c.calendarResourceId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.calendars.delete" call. +func (c *ResourcesCalendarsDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Deletes a calendar resource.", + // "httpMethod": "DELETE", + // "id": "directory.resources.calendars.delete", + // "parameterOrder": [ + // "customer", + // "calendarResourceId" + // ], + // "parameters": { + // "calendarResourceId": { + // "description": "The unique ID of the calendar resource to delete.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/calendars/{calendarResourceId}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar" + // ] + // } + +} + +// method id "directory.resources.calendars.get": + +type ResourcesCalendarsGetCall struct { + s *Service + customer string + calendarResourceId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieves a calendar resource. +func (r *ResourcesCalendarsService) Get(customer string, calendarResourceId string) *ResourcesCalendarsGetCall { + c := &ResourcesCalendarsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.calendarResourceId = calendarResourceId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesCalendarsGetCall) Fields(s ...googleapi.Field) *ResourcesCalendarsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *ResourcesCalendarsGetCall) IfNoneMatch(entityTag string) *ResourcesCalendarsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesCalendarsGetCall) Context(ctx context.Context) *ResourcesCalendarsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesCalendarsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesCalendarsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/calendars/{calendarResourceId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "calendarResourceId": c.calendarResourceId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.calendars.get" call. +// Exactly one of *CalendarResource or error will be non-nil. Any +// non-2xx status code is an error. Response headers are in either +// *CalendarResource.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *ResourcesCalendarsGetCall) Do(opts ...googleapi.CallOption) (*CalendarResource, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &CalendarResource{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a calendar resource.", + // "httpMethod": "GET", + // "id": "directory.resources.calendars.get", + // "parameterOrder": [ + // "customer", + // "calendarResourceId" + // ], + // "parameters": { + // "calendarResourceId": { + // "description": "The unique ID of the calendar resource to retrieve.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/calendars/{calendarResourceId}", + // "response": { + // "$ref": "CalendarResource" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar", + // "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" + // ] + // } + +} + +// method id "directory.resources.calendars.insert": + +type ResourcesCalendarsInsertCall struct { + s *Service + customer string + calendarresource *CalendarResource + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Inserts a calendar resource. +func (r *ResourcesCalendarsService) Insert(customer string, calendarresource *CalendarResource) *ResourcesCalendarsInsertCall { + c := &ResourcesCalendarsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.calendarresource = calendarresource + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesCalendarsInsertCall) Fields(s ...googleapi.Field) *ResourcesCalendarsInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesCalendarsInsertCall) Context(ctx context.Context) *ResourcesCalendarsInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesCalendarsInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesCalendarsInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.calendarresource) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/calendars") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.calendars.insert" call. +// Exactly one of *CalendarResource or error will be non-nil. Any +// non-2xx status code is an error. Response headers are in either +// *CalendarResource.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *ResourcesCalendarsInsertCall) Do(opts ...googleapi.CallOption) (*CalendarResource, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &CalendarResource{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Inserts a calendar resource.", + // "httpMethod": "POST", + // "id": "directory.resources.calendars.insert", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/calendars", + // "request": { + // "$ref": "CalendarResource" + // }, + // "response": { + // "$ref": "CalendarResource" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar" + // ] + // } + +} + +// method id "directory.resources.calendars.list": + +type ResourcesCalendarsListCall struct { + s *Service + customer string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieves a list of calendar resources for an account. +func (r *ResourcesCalendarsService) List(customer string) *ResourcesCalendarsListCall { + c := &ResourcesCalendarsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return. +func (c *ResourcesCalendarsListCall) MaxResults(maxResults int64) *ResourcesCalendarsListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// OrderBy sets the optional parameter "orderBy": Field(s) to sort +// results by in either ascending or descending order. Supported fields +// include resourceId, resourceName, capacity, buildingId, and +// floorName. If no order is specified, defaults to ascending. Should be +// of the form "field [asc|desc], field [asc|desc], ...". For example +// buildingId, capacity desc would return results sorted first by +// buildingId in ascending order then by capacity in descending order. +func (c *ResourcesCalendarsListCall) OrderBy(orderBy string) *ResourcesCalendarsListCall { + c.urlParams_.Set("orderBy", orderBy) + return c +} + +// PageToken sets the optional parameter "pageToken": Token to specify +// the next page in the list. +func (c *ResourcesCalendarsListCall) PageToken(pageToken string) *ResourcesCalendarsListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Query sets the optional parameter "query": String query used to +// filter results. Should be of the form "field operator value" where +// field can be any of supported fields and operators can be any of +// supported operations. Operators include '=' for exact match and ':' +// for prefix match or HAS match where applicable. For prefix match, the +// value should always be followed by a *. Supported fields include +// generatedResourceName, name, buildingId, +// featureInstances.feature.name. For example buildingId=US-NYC-9TH AND +// featureInstances.feature.name:Phone. +func (c *ResourcesCalendarsListCall) Query(query string) *ResourcesCalendarsListCall { + c.urlParams_.Set("query", query) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesCalendarsListCall) Fields(s ...googleapi.Field) *ResourcesCalendarsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *ResourcesCalendarsListCall) IfNoneMatch(entityTag string) *ResourcesCalendarsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesCalendarsListCall) Context(ctx context.Context) *ResourcesCalendarsListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesCalendarsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesCalendarsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/calendars") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.calendars.list" call. +// Exactly one of *CalendarResources or error will be non-nil. Any +// non-2xx status code is an error. Response headers are in either +// *CalendarResources.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *ResourcesCalendarsListCall) Do(opts ...googleapi.CallOption) (*CalendarResources, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &CalendarResources{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a list of calendar resources for an account.", + // "httpMethod": "GET", + // "id": "directory.resources.calendars.list", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "maxResults": { + // "description": "Maximum number of results to return.", + // "format": "int32", + // "location": "query", + // "maximum": "500", + // "minimum": "1", + // "type": "integer" + // }, + // "orderBy": { + // "description": "Field(s) to sort results by in either ascending or descending order. Supported fields include resourceId, resourceName, capacity, buildingId, and floorName. If no order is specified, defaults to ascending. Should be of the form \"field [asc|desc], field [asc|desc], ...\". For example buildingId, capacity desc would return results sorted first by buildingId in ascending order then by capacity in descending order.", + // "location": "query", + // "type": "string" + // }, + // "pageToken": { + // "description": "Token to specify the next page in the list.", + // "location": "query", + // "type": "string" + // }, + // "query": { + // "description": "String query used to filter results. Should be of the form \"field operator value\" where field can be any of supported fields and operators can be any of supported operations. Operators include '=' for exact match and ':' for prefix match or HAS match where applicable. For prefix match, the value should always be followed by a *. Supported fields include generatedResourceName, name, buildingId, featureInstances.feature.name. For example buildingId=US-NYC-9TH AND featureInstances.feature.name:Phone.", + // "location": "query", + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/calendars", + // "response": { + // "$ref": "CalendarResources" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar", + // "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *ResourcesCalendarsListCall) Pages(ctx context.Context, f func(*CalendarResources) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "directory.resources.calendars.patch": + +type ResourcesCalendarsPatchCall struct { + s *Service + customer string + calendarResourceId string + calendarresource *CalendarResource + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates a calendar resource. +// +// This method supports patch semantics, meaning you only need to +// include the fields you wish to update. Fields that are not present in +// the request will be preserved. This method supports patch semantics. +func (r *ResourcesCalendarsService) Patch(customer string, calendarResourceId string, calendarresource *CalendarResource) *ResourcesCalendarsPatchCall { + c := &ResourcesCalendarsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.calendarResourceId = calendarResourceId + c.calendarresource = calendarresource + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesCalendarsPatchCall) Fields(s ...googleapi.Field) *ResourcesCalendarsPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesCalendarsPatchCall) Context(ctx context.Context) *ResourcesCalendarsPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesCalendarsPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesCalendarsPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.calendarresource) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/calendars/{calendarResourceId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "calendarResourceId": c.calendarResourceId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.calendars.patch" call. +// Exactly one of *CalendarResource or error will be non-nil. Any +// non-2xx status code is an error. Response headers are in either +// *CalendarResource.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *ResourcesCalendarsPatchCall) Do(opts ...googleapi.CallOption) (*CalendarResource, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &CalendarResource{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates a calendar resource.\n\nThis method supports patch semantics, meaning you only need to include the fields you wish to update. Fields that are not present in the request will be preserved. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "directory.resources.calendars.patch", + // "parameterOrder": [ + // "customer", + // "calendarResourceId" + // ], + // "parameters": { + // "calendarResourceId": { + // "description": "The unique ID of the calendar resource to update.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/calendars/{calendarResourceId}", + // "request": { + // "$ref": "CalendarResource" + // }, + // "response": { + // "$ref": "CalendarResource" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar" + // ] + // } + +} + +// method id "directory.resources.calendars.update": + +type ResourcesCalendarsUpdateCall struct { + s *Service + customer string + calendarResourceId string + calendarresource *CalendarResource + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Updates a calendar resource. +// +// This method supports patch semantics, meaning you only need to +// include the fields you wish to update. Fields that are not present in +// the request will be preserved. +func (r *ResourcesCalendarsService) Update(customer string, calendarResourceId string, calendarresource *CalendarResource) *ResourcesCalendarsUpdateCall { + c := &ResourcesCalendarsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.calendarResourceId = calendarResourceId + c.calendarresource = calendarresource + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesCalendarsUpdateCall) Fields(s ...googleapi.Field) *ResourcesCalendarsUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesCalendarsUpdateCall) Context(ctx context.Context) *ResourcesCalendarsUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesCalendarsUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesCalendarsUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.calendarresource) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/calendars/{calendarResourceId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PUT", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "calendarResourceId": c.calendarResourceId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.calendars.update" call. +// Exactly one of *CalendarResource or error will be non-nil. Any +// non-2xx status code is an error. Response headers are in either +// *CalendarResource.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *ResourcesCalendarsUpdateCall) Do(opts ...googleapi.CallOption) (*CalendarResource, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &CalendarResource{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates a calendar resource.\n\nThis method supports patch semantics, meaning you only need to include the fields you wish to update. Fields that are not present in the request will be preserved.", + // "httpMethod": "PUT", + // "id": "directory.resources.calendars.update", + // "parameterOrder": [ + // "customer", + // "calendarResourceId" + // ], + // "parameters": { + // "calendarResourceId": { + // "description": "The unique ID of the calendar resource to update.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/calendars/{calendarResourceId}", + // "request": { + // "$ref": "CalendarResource" + // }, + // "response": { + // "$ref": "CalendarResource" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar" + // ] + // } + +} + +// method id "directory.resources.features.delete": + +type ResourcesFeaturesDeleteCall struct { + s *Service + customer string + featureKey string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes a feature. +func (r *ResourcesFeaturesService) Delete(customer string, featureKey string) *ResourcesFeaturesDeleteCall { + c := &ResourcesFeaturesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.featureKey = featureKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesFeaturesDeleteCall) Fields(s ...googleapi.Field) *ResourcesFeaturesDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesFeaturesDeleteCall) Context(ctx context.Context) *ResourcesFeaturesDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesFeaturesDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesFeaturesDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/features/{featureKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "featureKey": c.featureKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.features.delete" call. +func (c *ResourcesFeaturesDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Deletes a feature.", + // "httpMethod": "DELETE", + // "id": "directory.resources.features.delete", + // "parameterOrder": [ + // "customer", + // "featureKey" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "featureKey": { + // "description": "The unique ID of the feature to delete.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/features/{featureKey}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar" + // ] + // } + +} + +// method id "directory.resources.features.get": + +type ResourcesFeaturesGetCall struct { + s *Service + customer string + featureKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieves a feature. +func (r *ResourcesFeaturesService) Get(customer string, featureKey string) *ResourcesFeaturesGetCall { + c := &ResourcesFeaturesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.featureKey = featureKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesFeaturesGetCall) Fields(s ...googleapi.Field) *ResourcesFeaturesGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *ResourcesFeaturesGetCall) IfNoneMatch(entityTag string) *ResourcesFeaturesGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesFeaturesGetCall) Context(ctx context.Context) *ResourcesFeaturesGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesFeaturesGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesFeaturesGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/features/{featureKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "featureKey": c.featureKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.features.get" call. +// Exactly one of *Feature or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Feature.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *ResourcesFeaturesGetCall) Do(opts ...googleapi.CallOption) (*Feature, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Feature{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a feature.", + // "httpMethod": "GET", + // "id": "directory.resources.features.get", + // "parameterOrder": [ + // "customer", + // "featureKey" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "featureKey": { + // "description": "The unique ID of the feature to retrieve.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/features/{featureKey}", + // "response": { + // "$ref": "Feature" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar", + // "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" + // ] + // } + +} + +// method id "directory.resources.features.insert": + +type ResourcesFeaturesInsertCall struct { + s *Service + customer string + feature *Feature + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Inserts a feature. +func (r *ResourcesFeaturesService) Insert(customer string, feature *Feature) *ResourcesFeaturesInsertCall { + c := &ResourcesFeaturesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.feature = feature + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesFeaturesInsertCall) Fields(s ...googleapi.Field) *ResourcesFeaturesInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesFeaturesInsertCall) Context(ctx context.Context) *ResourcesFeaturesInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesFeaturesInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesFeaturesInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.feature) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/features") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.features.insert" call. +// Exactly one of *Feature or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Feature.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *ResourcesFeaturesInsertCall) Do(opts ...googleapi.CallOption) (*Feature, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Feature{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Inserts a feature.", + // "httpMethod": "POST", + // "id": "directory.resources.features.insert", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/features", + // "request": { + // "$ref": "Feature" + // }, + // "response": { + // "$ref": "Feature" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar" + // ] + // } + +} + +// method id "directory.resources.features.list": + +type ResourcesFeaturesListCall struct { + s *Service + customer string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieves a list of features for an account. +func (r *ResourcesFeaturesService) List(customer string) *ResourcesFeaturesListCall { + c := &ResourcesFeaturesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return. +func (c *ResourcesFeaturesListCall) MaxResults(maxResults int64) *ResourcesFeaturesListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// PageToken sets the optional parameter "pageToken": Token to specify +// the next page in the list. +func (c *ResourcesFeaturesListCall) PageToken(pageToken string) *ResourcesFeaturesListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesFeaturesListCall) Fields(s ...googleapi.Field) *ResourcesFeaturesListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *ResourcesFeaturesListCall) IfNoneMatch(entityTag string) *ResourcesFeaturesListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesFeaturesListCall) Context(ctx context.Context) *ResourcesFeaturesListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesFeaturesListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesFeaturesListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/features") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.features.list" call. +// Exactly one of *Features or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Features.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ResourcesFeaturesListCall) Do(opts ...googleapi.CallOption) (*Features, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Features{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a list of features for an account.", + // "httpMethod": "GET", + // "id": "directory.resources.features.list", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "maxResults": { + // "description": "Maximum number of results to return.", + // "format": "int32", + // "location": "query", + // "maximum": "500", + // "minimum": "1", + // "type": "integer" + // }, + // "pageToken": { + // "description": "Token to specify the next page in the list.", + // "location": "query", + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/features", + // "response": { + // "$ref": "Features" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar", + // "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *ResourcesFeaturesListCall) Pages(ctx context.Context, f func(*Features) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "directory.resources.features.patch": + +type ResourcesFeaturesPatchCall struct { + s *Service + customer string + featureKey string + feature *Feature + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates a feature. This method supports patch semantics. +func (r *ResourcesFeaturesService) Patch(customer string, featureKey string, feature *Feature) *ResourcesFeaturesPatchCall { + c := &ResourcesFeaturesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.featureKey = featureKey + c.feature = feature + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesFeaturesPatchCall) Fields(s ...googleapi.Field) *ResourcesFeaturesPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesFeaturesPatchCall) Context(ctx context.Context) *ResourcesFeaturesPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesFeaturesPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesFeaturesPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.feature) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/features/{featureKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "featureKey": c.featureKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.features.patch" call. +// Exactly one of *Feature or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Feature.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *ResourcesFeaturesPatchCall) Do(opts ...googleapi.CallOption) (*Feature, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Feature{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates a feature. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "directory.resources.features.patch", + // "parameterOrder": [ + // "customer", + // "featureKey" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "featureKey": { + // "description": "The unique ID of the feature to update.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/features/{featureKey}", + // "request": { + // "$ref": "Feature" + // }, + // "response": { + // "$ref": "Feature" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar" + // ] + // } + +} + +// method id "directory.resources.features.rename": + +type ResourcesFeaturesRenameCall struct { + s *Service + customer string + oldName string + featurerename *FeatureRename + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Rename: Renames a feature. +func (r *ResourcesFeaturesService) Rename(customer string, oldName string, featurerename *FeatureRename) *ResourcesFeaturesRenameCall { + c := &ResourcesFeaturesRenameCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.oldName = oldName + c.featurerename = featurerename + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesFeaturesRenameCall) Fields(s ...googleapi.Field) *ResourcesFeaturesRenameCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesFeaturesRenameCall) Context(ctx context.Context) *ResourcesFeaturesRenameCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesFeaturesRenameCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesFeaturesRenameCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.featurerename) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/features/{oldName}/rename") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "oldName": c.oldName, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.features.rename" call. +func (c *ResourcesFeaturesRenameCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Renames a feature.", + // "httpMethod": "POST", + // "id": "directory.resources.features.rename", + // "parameterOrder": [ + // "customer", + // "oldName" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "oldName": { + // "description": "The unique ID of the feature to rename.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/features/{oldName}/rename", + // "request": { + // "$ref": "FeatureRename" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar" + // ] + // } + +} + +// method id "directory.resources.features.update": + +type ResourcesFeaturesUpdateCall struct { + s *Service + customer string + featureKey string + feature *Feature + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Updates a feature. +func (r *ResourcesFeaturesService) Update(customer string, featureKey string, feature *Feature) *ResourcesFeaturesUpdateCall { + c := &ResourcesFeaturesUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.featureKey = featureKey + c.feature = feature + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ResourcesFeaturesUpdateCall) Fields(s ...googleapi.Field) *ResourcesFeaturesUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ResourcesFeaturesUpdateCall) Context(ctx context.Context) *ResourcesFeaturesUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ResourcesFeaturesUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ResourcesFeaturesUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.feature) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/features/{featureKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PUT", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "featureKey": c.featureKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.resources.features.update" call. +// Exactly one of *Feature or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Feature.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *ResourcesFeaturesUpdateCall) Do(opts ...googleapi.CallOption) (*Feature, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Feature{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates a feature.", + // "httpMethod": "PUT", + // "id": "directory.resources.features.update", + // "parameterOrder": [ + // "customer", + // "featureKey" + // ], + // "parameters": { + // "customer": { + // "description": "The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "featureKey": { + // "description": "The unique ID of the feature to update.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/resources/features/{featureKey}", + // "request": { + // "$ref": "Feature" + // }, + // "response": { + // "$ref": "Feature" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.resource.calendar" + // ] + // } + +} + +// method id "directory.roleAssignments.delete": + +type RoleAssignmentsDeleteCall struct { + s *Service + customer string + roleAssignmentId string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes a role assignment. +func (r *RoleAssignmentsService) Delete(customer string, roleAssignmentId string) *RoleAssignmentsDeleteCall { + c := &RoleAssignmentsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.roleAssignmentId = roleAssignmentId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *RoleAssignmentsDeleteCall) Fields(s ...googleapi.Field) *RoleAssignmentsDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *RoleAssignmentsDeleteCall) Context(ctx context.Context) *RoleAssignmentsDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *RoleAssignmentsDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *RoleAssignmentsDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roleassignments/{roleAssignmentId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "roleAssignmentId": c.roleAssignmentId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.roleAssignments.delete" call. +func (c *RoleAssignmentsDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Deletes a role assignment.", + // "httpMethod": "DELETE", + // "id": "directory.roleAssignments.delete", + // "parameterOrder": [ + // "customer", + // "roleAssignmentId" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "roleAssignmentId": { + // "description": "Immutable ID of the role assignment.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/roleassignments/{roleAssignmentId}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.rolemanagement" + // ] + // } + +} + +// method id "directory.roleAssignments.get": + +type RoleAssignmentsGetCall struct { + s *Service + customer string + roleAssignmentId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieve a role assignment. +func (r *RoleAssignmentsService) Get(customer string, roleAssignmentId string) *RoleAssignmentsGetCall { + c := &RoleAssignmentsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.roleAssignmentId = roleAssignmentId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *RoleAssignmentsGetCall) Fields(s ...googleapi.Field) *RoleAssignmentsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *RoleAssignmentsGetCall) IfNoneMatch(entityTag string) *RoleAssignmentsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *RoleAssignmentsGetCall) Context(ctx context.Context) *RoleAssignmentsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *RoleAssignmentsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *RoleAssignmentsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roleassignments/{roleAssignmentId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "roleAssignmentId": c.roleAssignmentId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.roleAssignments.get" call. +// Exactly one of *RoleAssignment or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *RoleAssignment.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *RoleAssignmentsGetCall) Do(opts ...googleapi.CallOption) (*RoleAssignment, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &RoleAssignment{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve a role assignment.", + // "httpMethod": "GET", + // "id": "directory.roleAssignments.get", + // "parameterOrder": [ + // "customer", + // "roleAssignmentId" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "roleAssignmentId": { + // "description": "Immutable ID of the role assignment.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/roleassignments/{roleAssignmentId}", + // "response": { + // "$ref": "RoleAssignment" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.rolemanagement", + // "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" + // ] + // } + +} + +// method id "directory.roleAssignments.insert": + +type RoleAssignmentsInsertCall struct { + s *Service + customer string + roleassignment *RoleAssignment + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Creates a role assignment. +func (r *RoleAssignmentsService) Insert(customer string, roleassignment *RoleAssignment) *RoleAssignmentsInsertCall { + c := &RoleAssignmentsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.roleassignment = roleassignment + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *RoleAssignmentsInsertCall) Fields(s ...googleapi.Field) *RoleAssignmentsInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *RoleAssignmentsInsertCall) Context(ctx context.Context) *RoleAssignmentsInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *RoleAssignmentsInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *RoleAssignmentsInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.roleassignment) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roleassignments") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.roleAssignments.insert" call. +// Exactly one of *RoleAssignment or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *RoleAssignment.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *RoleAssignmentsInsertCall) Do(opts ...googleapi.CallOption) (*RoleAssignment, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &RoleAssignment{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Creates a role assignment.", + // "httpMethod": "POST", + // "id": "directory.roleAssignments.insert", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/roleassignments", + // "request": { + // "$ref": "RoleAssignment" + // }, + // "response": { + // "$ref": "RoleAssignment" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.rolemanagement" + // ] + // } + +} + +// method id "directory.roleAssignments.list": + +type RoleAssignmentsListCall struct { + s *Service + customer string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieves a paginated list of all roleAssignments. +func (r *RoleAssignmentsService) List(customer string) *RoleAssignmentsListCall { + c := &RoleAssignmentsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return. +func (c *RoleAssignmentsListCall) MaxResults(maxResults int64) *RoleAssignmentsListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// PageToken sets the optional parameter "pageToken": Token to specify +// the next page in the list. +func (c *RoleAssignmentsListCall) PageToken(pageToken string) *RoleAssignmentsListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// RoleId sets the optional parameter "roleId": Immutable ID of a role. +// If included in the request, returns only role assignments containing +// this role ID. +func (c *RoleAssignmentsListCall) RoleId(roleId string) *RoleAssignmentsListCall { + c.urlParams_.Set("roleId", roleId) + return c +} + +// UserKey sets the optional parameter "userKey": The user's primary +// email address, alias email address, or unique user ID. If included in +// the request, returns role assignments only for this user. +func (c *RoleAssignmentsListCall) UserKey(userKey string) *RoleAssignmentsListCall { + c.urlParams_.Set("userKey", userKey) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *RoleAssignmentsListCall) Fields(s ...googleapi.Field) *RoleAssignmentsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *RoleAssignmentsListCall) IfNoneMatch(entityTag string) *RoleAssignmentsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *RoleAssignmentsListCall) Context(ctx context.Context) *RoleAssignmentsListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *RoleAssignmentsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *RoleAssignmentsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roleassignments") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.roleAssignments.list" call. +// Exactly one of *RoleAssignments or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *RoleAssignments.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *RoleAssignmentsListCall) Do(opts ...googleapi.CallOption) (*RoleAssignments, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &RoleAssignments{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a paginated list of all roleAssignments.", + // "httpMethod": "GET", + // "id": "directory.roleAssignments.list", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "maxResults": { + // "description": "Maximum number of results to return.", + // "format": "int32", + // "location": "query", + // "maximum": "200", + // "minimum": "1", + // "type": "integer" + // }, + // "pageToken": { + // "description": "Token to specify the next page in the list.", + // "location": "query", + // "type": "string" + // }, + // "roleId": { + // "description": "Immutable ID of a role. If included in the request, returns only role assignments containing this role ID.", + // "location": "query", + // "type": "string" + // }, + // "userKey": { + // "description": "The user's primary email address, alias email address, or unique user ID. If included in the request, returns role assignments only for this user.", + // "location": "query", + // "type": "string" + // } + // }, + // "path": "customer/{customer}/roleassignments", + // "response": { + // "$ref": "RoleAssignments" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.rolemanagement", + // "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *RoleAssignmentsListCall) Pages(ctx context.Context, f func(*RoleAssignments) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "directory.roles.delete": + +type RolesDeleteCall struct { + s *Service + customer string + roleId string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes a role. +func (r *RolesService) Delete(customer string, roleId string) *RolesDeleteCall { + c := &RolesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.roleId = roleId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *RolesDeleteCall) Fields(s ...googleapi.Field) *RolesDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *RolesDeleteCall) Context(ctx context.Context) *RolesDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *RolesDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *RolesDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles/{roleId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "roleId": c.roleId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.roles.delete" call. +func (c *RolesDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Deletes a role.", + // "httpMethod": "DELETE", + // "id": "directory.roles.delete", + // "parameterOrder": [ + // "customer", + // "roleId" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "roleId": { + // "description": "Immutable ID of the role.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/roles/{roleId}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.rolemanagement" + // ] + // } + +} + +// method id "directory.roles.get": + +type RolesGetCall struct { + s *Service + customer string + roleId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieves a role. +func (r *RolesService) Get(customer string, roleId string) *RolesGetCall { + c := &RolesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.roleId = roleId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *RolesGetCall) Fields(s ...googleapi.Field) *RolesGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *RolesGetCall) IfNoneMatch(entityTag string) *RolesGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *RolesGetCall) Context(ctx context.Context) *RolesGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *RolesGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *RolesGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles/{roleId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "roleId": c.roleId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.roles.get" call. +// Exactly one of *Role or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Role.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was +// returned. +func (c *RolesGetCall) Do(opts ...googleapi.CallOption) (*Role, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Role{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a role.", + // "httpMethod": "GET", + // "id": "directory.roles.get", + // "parameterOrder": [ + // "customer", + // "roleId" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "roleId": { + // "description": "Immutable ID of the role.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/roles/{roleId}", + // "response": { + // "$ref": "Role" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.rolemanagement", + // "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" + // ] + // } + +} + +// method id "directory.roles.insert": + +type RolesInsertCall struct { + s *Service + customer string + role *Role + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Creates a role. +func (r *RolesService) Insert(customer string, role *Role) *RolesInsertCall { + c := &RolesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.role = role + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *RolesInsertCall) Fields(s ...googleapi.Field) *RolesInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *RolesInsertCall) Context(ctx context.Context) *RolesInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *RolesInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *RolesInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.role) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.roles.insert" call. +// Exactly one of *Role or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Role.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was +// returned. +func (c *RolesInsertCall) Do(opts ...googleapi.CallOption) (*Role, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Role{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Creates a role.", + // "httpMethod": "POST", + // "id": "directory.roles.insert", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/roles", + // "request": { + // "$ref": "Role" + // }, + // "response": { + // "$ref": "Role" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.rolemanagement" + // ] + // } + +} + +// method id "directory.roles.list": + +type RolesListCall struct { + s *Service + customer string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieves a paginated list of all the roles in a domain. +func (r *RolesService) List(customer string) *RolesListCall { + c := &RolesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return. +func (c *RolesListCall) MaxResults(maxResults int64) *RolesListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// PageToken sets the optional parameter "pageToken": Token to specify +// the next page in the list. +func (c *RolesListCall) PageToken(pageToken string) *RolesListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *RolesListCall) Fields(s ...googleapi.Field) *RolesListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *RolesListCall) IfNoneMatch(entityTag string) *RolesListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *RolesListCall) Context(ctx context.Context) *RolesListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *RolesListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *RolesListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.roles.list" call. +// Exactly one of *Roles or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Roles.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *RolesListCall) Do(opts ...googleapi.CallOption) (*Roles, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Roles{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves a paginated list of all the roles in a domain.", + // "httpMethod": "GET", + // "id": "directory.roles.list", + // "parameterOrder": [ + // "customer" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "maxResults": { + // "description": "Maximum number of results to return.", + // "format": "int32", + // "location": "query", + // "maximum": "100", + // "minimum": "1", + // "type": "integer" + // }, + // "pageToken": { + // "description": "Token to specify the next page in the list.", + // "location": "query", + // "type": "string" + // } + // }, + // "path": "customer/{customer}/roles", + // "response": { + // "$ref": "Roles" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.rolemanagement", + // "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *RolesListCall) Pages(ctx context.Context, f func(*Roles) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "directory.roles.patch": + +type RolesPatchCall struct { + s *Service + customer string + roleId string + role *Role + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates a role. This method supports patch semantics. +func (r *RolesService) Patch(customer string, roleId string, role *Role) *RolesPatchCall { + c := &RolesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.roleId = roleId + c.role = role + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *RolesPatchCall) Fields(s ...googleapi.Field) *RolesPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *RolesPatchCall) Context(ctx context.Context) *RolesPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *RolesPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *RolesPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.role) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles/{roleId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "roleId": c.roleId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.roles.patch" call. +// Exactly one of *Role or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Role.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was +// returned. +func (c *RolesPatchCall) Do(opts ...googleapi.CallOption) (*Role, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Role{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates a role. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "directory.roles.patch", + // "parameterOrder": [ + // "customer", + // "roleId" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "roleId": { + // "description": "Immutable ID of the role.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/roles/{roleId}", + // "request": { + // "$ref": "Role" + // }, + // "response": { + // "$ref": "Role" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.rolemanagement" + // ] + // } + +} + +// method id "directory.roles.update": + +type RolesUpdateCall struct { + s *Service + customer string + roleId string + role *Role + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Updates a role. +func (r *RolesService) Update(customer string, roleId string, role *Role) *RolesUpdateCall { + c := &RolesUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customer = customer + c.roleId = roleId + c.role = role + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *RolesUpdateCall) Fields(s ...googleapi.Field) *RolesUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *RolesUpdateCall) Context(ctx context.Context) *RolesUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *RolesUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *RolesUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.role) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles/{roleId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PUT", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customer": c.customer, + "roleId": c.roleId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.roles.update" call. +// Exactly one of *Role or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Role.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was +// returned. +func (c *RolesUpdateCall) Do(opts ...googleapi.CallOption) (*Role, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Role{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates a role.", + // "httpMethod": "PUT", + // "id": "directory.roles.update", + // "parameterOrder": [ + // "customer", + // "roleId" + // ], + // "parameters": { + // "customer": { + // "description": "Immutable ID of the G Suite account.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "roleId": { + // "description": "Immutable ID of the role.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customer}/roles/{roleId}", + // "request": { + // "$ref": "Role" + // }, + // "response": { + // "$ref": "Role" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.rolemanagement" + // ] + // } + +} + +// method id "directory.schemas.delete": + +type SchemasDeleteCall struct { + s *Service + customerId string + schemaKey string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Delete schema +func (r *SchemasService) Delete(customerId string, schemaKey string) *SchemasDeleteCall { + c := &SchemasDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.schemaKey = schemaKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *SchemasDeleteCall) Fields(s ...googleapi.Field) *SchemasDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *SchemasDeleteCall) Context(ctx context.Context) *SchemasDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *SchemasDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *SchemasDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/schemas/{schemaKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "schemaKey": c.schemaKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.schemas.delete" call. +func (c *SchemasDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Delete schema", + // "httpMethod": "DELETE", + // "id": "directory.schemas.delete", + // "parameterOrder": [ + // "customerId", + // "schemaKey" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "schemaKey": { + // "description": "Name or immutable ID of the schema", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/schemas/{schemaKey}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.userschema" + // ] + // } + +} + +// method id "directory.schemas.get": + +type SchemasGetCall struct { + s *Service + customerId string + schemaKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieve schema +func (r *SchemasService) Get(customerId string, schemaKey string) *SchemasGetCall { + c := &SchemasGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.schemaKey = schemaKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *SchemasGetCall) Fields(s ...googleapi.Field) *SchemasGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *SchemasGetCall) IfNoneMatch(entityTag string) *SchemasGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *SchemasGetCall) Context(ctx context.Context) *SchemasGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *SchemasGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *SchemasGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/schemas/{schemaKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "schemaKey": c.schemaKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.schemas.get" call. +// Exactly one of *Schema or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Schema.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *SchemasGetCall) Do(opts ...googleapi.CallOption) (*Schema, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Schema{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve schema", + // "httpMethod": "GET", + // "id": "directory.schemas.get", + // "parameterOrder": [ + // "customerId", + // "schemaKey" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "schemaKey": { + // "description": "Name or immutable ID of the schema", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/schemas/{schemaKey}", + // "response": { + // "$ref": "Schema" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.userschema", + // "https://www.googleapis.com/auth/admin.directory.userschema.readonly" + // ] + // } + +} + +// method id "directory.schemas.insert": + +type SchemasInsertCall struct { + s *Service + customerId string + schema *Schema + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Create schema. +func (r *SchemasService) Insert(customerId string, schema *Schema) *SchemasInsertCall { + c := &SchemasInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.schema = schema + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *SchemasInsertCall) Fields(s ...googleapi.Field) *SchemasInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *SchemasInsertCall) Context(ctx context.Context) *SchemasInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *SchemasInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *SchemasInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.schema) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/schemas") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.schemas.insert" call. +// Exactly one of *Schema or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Schema.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *SchemasInsertCall) Do(opts ...googleapi.CallOption) (*Schema, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Schema{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Create schema.", + // "httpMethod": "POST", + // "id": "directory.schemas.insert", + // "parameterOrder": [ + // "customerId" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/schemas", + // "request": { + // "$ref": "Schema" + // }, + // "response": { + // "$ref": "Schema" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.userschema" + // ] + // } + +} + +// method id "directory.schemas.list": + +type SchemasListCall struct { + s *Service + customerId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieve all schemas for a customer +func (r *SchemasService) List(customerId string) *SchemasListCall { + c := &SchemasListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *SchemasListCall) Fields(s ...googleapi.Field) *SchemasListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *SchemasListCall) IfNoneMatch(entityTag string) *SchemasListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *SchemasListCall) Context(ctx context.Context) *SchemasListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *SchemasListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *SchemasListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/schemas") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.schemas.list" call. +// Exactly one of *Schemas or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Schemas.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *SchemasListCall) Do(opts ...googleapi.CallOption) (*Schemas, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Schemas{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve all schemas for a customer", + // "httpMethod": "GET", + // "id": "directory.schemas.list", + // "parameterOrder": [ + // "customerId" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/schemas", + // "response": { + // "$ref": "Schemas" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.userschema", + // "https://www.googleapis.com/auth/admin.directory.userschema.readonly" + // ] + // } + +} + +// method id "directory.schemas.patch": + +type SchemasPatchCall struct { + s *Service + customerId string + schemaKey string + schema *Schema + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Update schema. This method supports patch semantics. +func (r *SchemasService) Patch(customerId string, schemaKey string, schema *Schema) *SchemasPatchCall { + c := &SchemasPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.schemaKey = schemaKey + c.schema = schema + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *SchemasPatchCall) Fields(s ...googleapi.Field) *SchemasPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *SchemasPatchCall) Context(ctx context.Context) *SchemasPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *SchemasPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *SchemasPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.schema) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/schemas/{schemaKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "schemaKey": c.schemaKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.schemas.patch" call. +// Exactly one of *Schema or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Schema.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *SchemasPatchCall) Do(opts ...googleapi.CallOption) (*Schema, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Schema{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Update schema. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "directory.schemas.patch", + // "parameterOrder": [ + // "customerId", + // "schemaKey" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "schemaKey": { + // "description": "Name or immutable ID of the schema.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/schemas/{schemaKey}", + // "request": { + // "$ref": "Schema" + // }, + // "response": { + // "$ref": "Schema" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.userschema" + // ] + // } + +} + +// method id "directory.schemas.update": + +type SchemasUpdateCall struct { + s *Service + customerId string + schemaKey string + schema *Schema + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Update schema +func (r *SchemasService) Update(customerId string, schemaKey string, schema *Schema) *SchemasUpdateCall { + c := &SchemasUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.customerId = customerId + c.schemaKey = schemaKey + c.schema = schema + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *SchemasUpdateCall) Fields(s ...googleapi.Field) *SchemasUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *SchemasUpdateCall) Context(ctx context.Context) *SchemasUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *SchemasUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *SchemasUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.schema) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/schemas/{schemaKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PUT", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "customerId": c.customerId, + "schemaKey": c.schemaKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.schemas.update" call. +// Exactly one of *Schema or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Schema.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *SchemasUpdateCall) Do(opts ...googleapi.CallOption) (*Schema, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Schema{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Update schema", + // "httpMethod": "PUT", + // "id": "directory.schemas.update", + // "parameterOrder": [ + // "customerId", + // "schemaKey" + // ], + // "parameters": { + // "customerId": { + // "description": "Immutable ID of the G Suite account", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "schemaKey": { + // "description": "Name or immutable ID of the schema.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "customer/{customerId}/schemas/{schemaKey}", + // "request": { + // "$ref": "Schema" + // }, + // "response": { + // "$ref": "Schema" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.userschema" + // ] + // } + +} + +// method id "directory.tokens.delete": + +type TokensDeleteCall struct { + s *Service + userKey string + clientId string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Delete all access tokens issued by a user for an application. +func (r *TokensService) Delete(userKey string, clientId string) *TokensDeleteCall { + c := &TokensDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + c.clientId = clientId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *TokensDeleteCall) Fields(s ...googleapi.Field) *TokensDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *TokensDeleteCall) Context(ctx context.Context) *TokensDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *TokensDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TokensDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/tokens/{clientId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + "clientId": c.clientId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.tokens.delete" call. +func (c *TokensDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Delete all access tokens issued by a user for an application.", + // "httpMethod": "DELETE", + // "id": "directory.tokens.delete", + // "parameterOrder": [ + // "userKey", + // "clientId" + // ], + // "parameters": { + // "clientId": { + // "description": "The Client ID of the application the token is issued to.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "userKey": { + // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/tokens/{clientId}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user.security" + // ] + // } + +} + +// method id "directory.tokens.get": + +type TokensGetCall struct { + s *Service + userKey string + clientId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Get information about an access token issued by a user. +func (r *TokensService) Get(userKey string, clientId string) *TokensGetCall { + c := &TokensGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + c.clientId = clientId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *TokensGetCall) Fields(s ...googleapi.Field) *TokensGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *TokensGetCall) IfNoneMatch(entityTag string) *TokensGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *TokensGetCall) Context(ctx context.Context) *TokensGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *TokensGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TokensGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/tokens/{clientId}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + "clientId": c.clientId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.tokens.get" call. +// Exactly one of *Token or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Token.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *TokensGetCall) Do(opts ...googleapi.CallOption) (*Token, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Token{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Get information about an access token issued by a user.", + // "httpMethod": "GET", + // "id": "directory.tokens.get", + // "parameterOrder": [ + // "userKey", + // "clientId" + // ], + // "parameters": { + // "clientId": { + // "description": "The Client ID of the application the token is issued to.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "userKey": { + // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/tokens/{clientId}", + // "response": { + // "$ref": "Token" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user.security" + // ] + // } + +} + +// method id "directory.tokens.list": + +type TokensListCall struct { + s *Service + userKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Returns the set of tokens specified user has issued to 3rd +// party applications. +func (r *TokensService) List(userKey string) *TokensListCall { + c := &TokensListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *TokensListCall) Fields(s ...googleapi.Field) *TokensListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *TokensListCall) IfNoneMatch(entityTag string) *TokensListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *TokensListCall) Context(ctx context.Context) *TokensListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *TokensListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TokensListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/tokens") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.tokens.list" call. +// Exactly one of *Tokens or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Tokens.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *TokensListCall) Do(opts ...googleapi.CallOption) (*Tokens, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Tokens{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Returns the set of tokens specified user has issued to 3rd party applications.", + // "httpMethod": "GET", + // "id": "directory.tokens.list", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/tokens", + // "response": { + // "$ref": "Tokens" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user.security" + // ] + // } + +} + +// method id "directory.users.delete": + +type UsersDeleteCall struct { + s *Service + userKey string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Delete user +func (r *UsersService) Delete(userKey string) *UsersDeleteCall { + c := &UsersDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersDeleteCall) Fields(s ...googleapi.Field) *UsersDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersDeleteCall) Context(ctx context.Context) *UsersDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.delete" call. +func (c *UsersDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Delete user", + // "httpMethod": "DELETE", + // "id": "directory.users.delete", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Email or immutable ID of the user", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user" + // ] + // } + +} + +// method id "directory.users.get": + +type UsersGetCall struct { + s *Service + userKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: retrieve user +func (r *UsersService) Get(userKey string) *UsersGetCall { + c := &UsersGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + return c +} + +// CustomFieldMask sets the optional parameter "customFieldMask": +// Comma-separated list of schema names. All fields from these schemas +// are fetched. This should only be set when projection=custom. +func (c *UsersGetCall) CustomFieldMask(customFieldMask string) *UsersGetCall { + c.urlParams_.Set("customFieldMask", customFieldMask) + return c +} + +// Projection sets the optional parameter "projection": What subset of +// fields to fetch for this user. +// +// Possible values: +// "basic" (default) - Do not include any custom fields for the user. +// "custom" - Include custom fields from schemas mentioned in +// customFieldMask. +// "full" - Include all fields associated with this user. +func (c *UsersGetCall) Projection(projection string) *UsersGetCall { + c.urlParams_.Set("projection", projection) + return c +} + +// ViewType sets the optional parameter "viewType": Whether to fetch the +// ADMIN_VIEW or DOMAIN_PUBLIC view of the user. +// +// Possible values: +// "admin_view" (default) - Fetches the ADMIN_VIEW of the user. +// "domain_public" - Fetches the DOMAIN_PUBLIC view of the user. +func (c *UsersGetCall) ViewType(viewType string) *UsersGetCall { + c.urlParams_.Set("viewType", viewType) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersGetCall) Fields(s ...googleapi.Field) *UsersGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *UsersGetCall) IfNoneMatch(entityTag string) *UsersGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersGetCall) Context(ctx context.Context) *UsersGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.get" call. +// Exactly one of *User or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *User.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was +// returned. +func (c *UsersGetCall) Do(opts ...googleapi.CallOption) (*User, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &User{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "retrieve user", + // "httpMethod": "GET", + // "id": "directory.users.get", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "customFieldMask": { + // "description": "Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.", + // "location": "query", + // "type": "string" + // }, + // "projection": { + // "default": "basic", + // "description": "What subset of fields to fetch for this user.", + // "enum": [ + // "basic", + // "custom", + // "full" + // ], + // "enumDescriptions": [ + // "Do not include any custom fields for the user.", + // "Include custom fields from schemas mentioned in customFieldMask.", + // "Include all fields associated with this user." + // ], + // "location": "query", + // "type": "string" + // }, + // "userKey": { + // "description": "Email or immutable ID of the user", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "viewType": { + // "default": "admin_view", + // "description": "Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.", + // "enum": [ + // "admin_view", + // "domain_public" + // ], + // "enumDescriptions": [ + // "Fetches the ADMIN_VIEW of the user.", + // "Fetches the DOMAIN_PUBLIC view of the user." + // ], + // "location": "query", + // "type": "string" + // } + // }, + // "path": "users/{userKey}", + // "response": { + // "$ref": "User" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user", + // "https://www.googleapis.com/auth/admin.directory.user.readonly" + // ] + // } + +} + +// method id "directory.users.insert": + +type UsersInsertCall struct { + s *Service + user *User + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: create user. +func (r *UsersService) Insert(user *User) *UsersInsertCall { + c := &UsersInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.user = user + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersInsertCall) Fields(s ...googleapi.Field) *UsersInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersInsertCall) Context(ctx context.Context) *UsersInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.user) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.insert" call. +// Exactly one of *User or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *User.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was +// returned. +func (c *UsersInsertCall) Do(opts ...googleapi.CallOption) (*User, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &User{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "create user.", + // "httpMethod": "POST", + // "id": "directory.users.insert", + // "path": "users", + // "request": { + // "$ref": "User" + // }, + // "response": { + // "$ref": "User" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user" + // ] + // } + +} + +// method id "directory.users.list": + +type UsersListCall struct { + s *Service + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieve either deleted users or all users in a domain +// (paginated) +func (r *UsersService) List() *UsersListCall { + c := &UsersListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + return c +} + +// CustomFieldMask sets the optional parameter "customFieldMask": +// Comma-separated list of schema names. All fields from these schemas +// are fetched. This should only be set when projection=custom. +func (c *UsersListCall) CustomFieldMask(customFieldMask string) *UsersListCall { + c.urlParams_.Set("customFieldMask", customFieldMask) + return c +} + +// Customer sets the optional parameter "customer": Immutable ID of the +// G Suite account. In case of multi-domain, to fetch all users for a +// customer, fill this field instead of domain. +func (c *UsersListCall) Customer(customer string) *UsersListCall { + c.urlParams_.Set("customer", customer) + return c +} + +// Domain sets the optional parameter "domain": Name of the domain. Fill +// this field to get users from only this domain. To return all users in +// a multi-domain fill customer field instead. +func (c *UsersListCall) Domain(domain string) *UsersListCall { + c.urlParams_.Set("domain", domain) + return c +} + +// Event sets the optional parameter "event": Event on which +// subscription is intended (if subscribing) +// +// Possible values: +// "add" - User Created Event +// "delete" - User Deleted Event +// "makeAdmin" - User Admin Status Change Event +// "undelete" - User Undeleted Event +// "update" - User Updated Event +func (c *UsersListCall) Event(event string) *UsersListCall { + c.urlParams_.Set("event", event) + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return. +func (c *UsersListCall) MaxResults(maxResults int64) *UsersListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// OrderBy sets the optional parameter "orderBy": Column to use for +// sorting results +// +// Possible values: +// "email" - Primary email of the user. +// "familyName" - User's family name. +// "givenName" - User's given name. +func (c *UsersListCall) OrderBy(orderBy string) *UsersListCall { + c.urlParams_.Set("orderBy", orderBy) + return c +} + +// PageToken sets the optional parameter "pageToken": Token to specify +// next page in the list +func (c *UsersListCall) PageToken(pageToken string) *UsersListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Projection sets the optional parameter "projection": What subset of +// fields to fetch for this user. +// +// Possible values: +// "basic" (default) - Do not include any custom fields for the user. +// "custom" - Include custom fields from schemas mentioned in +// customFieldMask. +// "full" - Include all fields associated with this user. +func (c *UsersListCall) Projection(projection string) *UsersListCall { + c.urlParams_.Set("projection", projection) + return c +} + +// Query sets the optional parameter "query": Query string search. +// Should be of the form "". Complete documentation is at +// https://developers.google.com/admin-sdk/directory/v1/guides/search-users +func (c *UsersListCall) Query(query string) *UsersListCall { + c.urlParams_.Set("query", query) + return c +} + +// ShowDeleted sets the optional parameter "showDeleted": If set to +// true, retrieves the list of deleted users. (Default: false) +func (c *UsersListCall) ShowDeleted(showDeleted string) *UsersListCall { + c.urlParams_.Set("showDeleted", showDeleted) + return c +} + +// SortOrder sets the optional parameter "sortOrder": Whether to return +// results in ascending or descending order. +// +// Possible values: +// "ASCENDING" - Ascending order. +// "DESCENDING" - Descending order. +func (c *UsersListCall) SortOrder(sortOrder string) *UsersListCall { + c.urlParams_.Set("sortOrder", sortOrder) + return c +} + +// ViewType sets the optional parameter "viewType": Whether to fetch the +// ADMIN_VIEW or DOMAIN_PUBLIC view of the user. +// +// Possible values: +// "admin_view" (default) - Fetches the ADMIN_VIEW of the user. +// "domain_public" - Fetches the DOMAIN_PUBLIC view of the user. +func (c *UsersListCall) ViewType(viewType string) *UsersListCall { + c.urlParams_.Set("viewType", viewType) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersListCall) Fields(s ...googleapi.Field) *UsersListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *UsersListCall) IfNoneMatch(entityTag string) *UsersListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersListCall) Context(ctx context.Context) *UsersListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.list" call. +// Exactly one of *Users or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Users.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *UsersListCall) Do(opts ...googleapi.CallOption) (*Users, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Users{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve either deleted users or all users in a domain (paginated)", + // "httpMethod": "GET", + // "id": "directory.users.list", + // "parameters": { + // "customFieldMask": { + // "description": "Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.", + // "location": "query", + // "type": "string" + // }, + // "customer": { + // "description": "Immutable ID of the G Suite account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain.", + // "location": "query", + // "type": "string" + // }, + // "domain": { + // "description": "Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead.", + // "location": "query", + // "type": "string" + // }, + // "event": { + // "description": "Event on which subscription is intended (if subscribing)", + // "enum": [ + // "add", + // "delete", + // "makeAdmin", + // "undelete", + // "update" + // ], + // "enumDescriptions": [ + // "User Created Event", + // "User Deleted Event", + // "User Admin Status Change Event", + // "User Undeleted Event", + // "User Updated Event" + // ], + // "location": "query", + // "type": "string" + // }, + // "maxResults": { + // "default": "100", + // "description": "Maximum number of results to return.", + // "format": "int32", + // "location": "query", + // "maximum": "500", + // "minimum": "1", + // "type": "integer" + // }, + // "orderBy": { + // "description": "Column to use for sorting results", + // "enum": [ + // "email", + // "familyName", + // "givenName" + // ], + // "enumDescriptions": [ + // "Primary email of the user.", + // "User's family name.", + // "User's given name." + // ], + // "location": "query", + // "type": "string" + // }, + // "pageToken": { + // "description": "Token to specify next page in the list", + // "location": "query", + // "type": "string" + // }, + // "projection": { + // "default": "basic", + // "description": "What subset of fields to fetch for this user.", + // "enum": [ + // "basic", + // "custom", + // "full" + // ], + // "enumDescriptions": [ + // "Do not include any custom fields for the user.", + // "Include custom fields from schemas mentioned in customFieldMask.", + // "Include all fields associated with this user." + // ], + // "location": "query", + // "type": "string" + // }, + // "query": { + // "description": "Query string search. Should be of the form \"\". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users", + // "location": "query", + // "type": "string" + // }, + // "showDeleted": { + // "description": "If set to true, retrieves the list of deleted users. (Default: false)", + // "location": "query", + // "type": "string" + // }, + // "sortOrder": { + // "description": "Whether to return results in ascending or descending order.", + // "enum": [ + // "ASCENDING", + // "DESCENDING" + // ], + // "enumDescriptions": [ + // "Ascending order.", + // "Descending order." + // ], + // "location": "query", + // "type": "string" + // }, + // "viewType": { + // "default": "admin_view", + // "description": "Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.", + // "enum": [ + // "admin_view", + // "domain_public" + // ], + // "enumDescriptions": [ + // "Fetches the ADMIN_VIEW of the user.", + // "Fetches the DOMAIN_PUBLIC view of the user." + // ], + // "location": "query", + // "type": "string" + // } + // }, + // "path": "users", + // "response": { + // "$ref": "Users" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user", + // "https://www.googleapis.com/auth/admin.directory.user.readonly" + // ], + // "supportsSubscription": true + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *UsersListCall) Pages(ctx context.Context, f func(*Users) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "directory.users.makeAdmin": + +type UsersMakeAdminCall struct { + s *Service + userKey string + usermakeadmin *UserMakeAdmin + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// MakeAdmin: change admin status of a user +func (r *UsersService) MakeAdmin(userKey string, usermakeadmin *UserMakeAdmin) *UsersMakeAdminCall { + c := &UsersMakeAdminCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + c.usermakeadmin = usermakeadmin + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersMakeAdminCall) Fields(s ...googleapi.Field) *UsersMakeAdminCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersMakeAdminCall) Context(ctx context.Context) *UsersMakeAdminCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersMakeAdminCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersMakeAdminCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.usermakeadmin) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/makeAdmin") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.makeAdmin" call. +func (c *UsersMakeAdminCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "change admin status of a user", + // "httpMethod": "POST", + // "id": "directory.users.makeAdmin", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Email or immutable ID of the user as admin", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/makeAdmin", + // "request": { + // "$ref": "UserMakeAdmin" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user" + // ] + // } + +} + +// method id "directory.users.patch": + +type UsersPatchCall struct { + s *Service + userKey string + user *User + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: update user. This method supports patch semantics. +func (r *UsersService) Patch(userKey string, user *User) *UsersPatchCall { + c := &UsersPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + c.user = user + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersPatchCall) Fields(s ...googleapi.Field) *UsersPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersPatchCall) Context(ctx context.Context) *UsersPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.user) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.patch" call. +// Exactly one of *User or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *User.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was +// returned. +func (c *UsersPatchCall) Do(opts ...googleapi.CallOption) (*User, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &User{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "update user. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "directory.users.patch", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Email or immutable ID of the user. If ID, it should match with id of user object", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}", + // "request": { + // "$ref": "User" + // }, + // "response": { + // "$ref": "User" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user" + // ] + // } + +} + +// method id "directory.users.undelete": + +type UsersUndeleteCall struct { + s *Service + userKey string + userundelete *UserUndelete + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Undelete: Undelete a deleted user +func (r *UsersService) Undelete(userKey string, userundelete *UserUndelete) *UsersUndeleteCall { + c := &UsersUndeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + c.userundelete = userundelete + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersUndeleteCall) Fields(s ...googleapi.Field) *UsersUndeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersUndeleteCall) Context(ctx context.Context) *UsersUndeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersUndeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersUndeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.userundelete) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/undelete") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.undelete" call. +func (c *UsersUndeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Undelete a deleted user", + // "httpMethod": "POST", + // "id": "directory.users.undelete", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "The immutable id of the user", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/undelete", + // "request": { + // "$ref": "UserUndelete" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user" + // ] + // } + +} + +// method id "directory.users.update": + +type UsersUpdateCall struct { + s *Service + userKey string + user *User + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: update user +func (r *UsersService) Update(userKey string, user *User) *UsersUpdateCall { + c := &UsersUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + c.user = user + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersUpdateCall) Fields(s ...googleapi.Field) *UsersUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersUpdateCall) Context(ctx context.Context) *UsersUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.user) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PUT", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.update" call. +// Exactly one of *User or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *User.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was +// returned. +func (c *UsersUpdateCall) Do(opts ...googleapi.CallOption) (*User, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &User{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "update user", + // "httpMethod": "PUT", + // "id": "directory.users.update", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Email or immutable ID of the user. If ID, it should match with id of user object", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}", + // "request": { + // "$ref": "User" + // }, + // "response": { + // "$ref": "User" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user" + // ] + // } + +} + +// method id "directory.users.watch": + +type UsersWatchCall struct { + s *Service + channel *Channel + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Watch: Watch for changes in users list +func (r *UsersService) Watch(channel *Channel) *UsersWatchCall { + c := &UsersWatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.channel = channel + return c +} + +// CustomFieldMask sets the optional parameter "customFieldMask": +// Comma-separated list of schema names. All fields from these schemas +// are fetched. This should only be set when projection=custom. +func (c *UsersWatchCall) CustomFieldMask(customFieldMask string) *UsersWatchCall { + c.urlParams_.Set("customFieldMask", customFieldMask) + return c +} + +// Customer sets the optional parameter "customer": Immutable ID of the +// G Suite account. In case of multi-domain, to fetch all users for a +// customer, fill this field instead of domain. +func (c *UsersWatchCall) Customer(customer string) *UsersWatchCall { + c.urlParams_.Set("customer", customer) + return c +} + +// Domain sets the optional parameter "domain": Name of the domain. Fill +// this field to get users from only this domain. To return all users in +// a multi-domain fill customer field instead. +func (c *UsersWatchCall) Domain(domain string) *UsersWatchCall { + c.urlParams_.Set("domain", domain) + return c +} + +// Event sets the optional parameter "event": Event on which +// subscription is intended (if subscribing) +// +// Possible values: +// "add" - User Created Event +// "delete" - User Deleted Event +// "makeAdmin" - User Admin Status Change Event +// "undelete" - User Undeleted Event +// "update" - User Updated Event +func (c *UsersWatchCall) Event(event string) *UsersWatchCall { + c.urlParams_.Set("event", event) + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return. +func (c *UsersWatchCall) MaxResults(maxResults int64) *UsersWatchCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// OrderBy sets the optional parameter "orderBy": Column to use for +// sorting results +// +// Possible values: +// "email" - Primary email of the user. +// "familyName" - User's family name. +// "givenName" - User's given name. +func (c *UsersWatchCall) OrderBy(orderBy string) *UsersWatchCall { + c.urlParams_.Set("orderBy", orderBy) + return c +} + +// PageToken sets the optional parameter "pageToken": Token to specify +// next page in the list +func (c *UsersWatchCall) PageToken(pageToken string) *UsersWatchCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Projection sets the optional parameter "projection": What subset of +// fields to fetch for this user. +// +// Possible values: +// "basic" (default) - Do not include any custom fields for the user. +// "custom" - Include custom fields from schemas mentioned in +// customFieldMask. +// "full" - Include all fields associated with this user. +func (c *UsersWatchCall) Projection(projection string) *UsersWatchCall { + c.urlParams_.Set("projection", projection) + return c +} + +// Query sets the optional parameter "query": Query string search. +// Should be of the form "". Complete documentation is at +// https://developers.google.com/admin-sdk/directory/v1/guides/search-users +func (c *UsersWatchCall) Query(query string) *UsersWatchCall { + c.urlParams_.Set("query", query) + return c +} + +// ShowDeleted sets the optional parameter "showDeleted": If set to +// true, retrieves the list of deleted users. (Default: false) +func (c *UsersWatchCall) ShowDeleted(showDeleted string) *UsersWatchCall { + c.urlParams_.Set("showDeleted", showDeleted) + return c +} + +// SortOrder sets the optional parameter "sortOrder": Whether to return +// results in ascending or descending order. +// +// Possible values: +// "ASCENDING" - Ascending order. +// "DESCENDING" - Descending order. +func (c *UsersWatchCall) SortOrder(sortOrder string) *UsersWatchCall { + c.urlParams_.Set("sortOrder", sortOrder) + return c +} + +// ViewType sets the optional parameter "viewType": Whether to fetch the +// ADMIN_VIEW or DOMAIN_PUBLIC view of the user. +// +// Possible values: +// "admin_view" (default) - Fetches the ADMIN_VIEW of the user. +// "domain_public" - Fetches the DOMAIN_PUBLIC view of the user. +func (c *UsersWatchCall) ViewType(viewType string) *UsersWatchCall { + c.urlParams_.Set("viewType", viewType) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersWatchCall) Fields(s ...googleapi.Field) *UsersWatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersWatchCall) Context(ctx context.Context) *UsersWatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersWatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersWatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.channel) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/watch") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.watch" call. +// Exactly one of *Channel or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Channel.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *UsersWatchCall) Do(opts ...googleapi.CallOption) (*Channel, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Channel{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Watch for changes in users list", + // "httpMethod": "POST", + // "id": "directory.users.watch", + // "parameters": { + // "customFieldMask": { + // "description": "Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.", + // "location": "query", + // "type": "string" + // }, + // "customer": { + // "description": "Immutable ID of the G Suite account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain.", + // "location": "query", + // "type": "string" + // }, + // "domain": { + // "description": "Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead.", + // "location": "query", + // "type": "string" + // }, + // "event": { + // "description": "Event on which subscription is intended (if subscribing)", + // "enum": [ + // "add", + // "delete", + // "makeAdmin", + // "undelete", + // "update" + // ], + // "enumDescriptions": [ + // "User Created Event", + // "User Deleted Event", + // "User Admin Status Change Event", + // "User Undeleted Event", + // "User Updated Event" + // ], + // "location": "query", + // "type": "string" + // }, + // "maxResults": { + // "default": "100", + // "description": "Maximum number of results to return.", + // "format": "int32", + // "location": "query", + // "maximum": "500", + // "minimum": "1", + // "type": "integer" + // }, + // "orderBy": { + // "description": "Column to use for sorting results", + // "enum": [ + // "email", + // "familyName", + // "givenName" + // ], + // "enumDescriptions": [ + // "Primary email of the user.", + // "User's family name.", + // "User's given name." + // ], + // "location": "query", + // "type": "string" + // }, + // "pageToken": { + // "description": "Token to specify next page in the list", + // "location": "query", + // "type": "string" + // }, + // "projection": { + // "default": "basic", + // "description": "What subset of fields to fetch for this user.", + // "enum": [ + // "basic", + // "custom", + // "full" + // ], + // "enumDescriptions": [ + // "Do not include any custom fields for the user.", + // "Include custom fields from schemas mentioned in customFieldMask.", + // "Include all fields associated with this user." + // ], + // "location": "query", + // "type": "string" + // }, + // "query": { + // "description": "Query string search. Should be of the form \"\". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users", + // "location": "query", + // "type": "string" + // }, + // "showDeleted": { + // "description": "If set to true, retrieves the list of deleted users. (Default: false)", + // "location": "query", + // "type": "string" + // }, + // "sortOrder": { + // "description": "Whether to return results in ascending or descending order.", + // "enum": [ + // "ASCENDING", + // "DESCENDING" + // ], + // "enumDescriptions": [ + // "Ascending order.", + // "Descending order." + // ], + // "location": "query", + // "type": "string" + // }, + // "viewType": { + // "default": "admin_view", + // "description": "Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.", + // "enum": [ + // "admin_view", + // "domain_public" + // ], + // "enumDescriptions": [ + // "Fetches the ADMIN_VIEW of the user.", + // "Fetches the DOMAIN_PUBLIC view of the user." + // ], + // "location": "query", + // "type": "string" + // } + // }, + // "path": "users/watch", + // "request": { + // "$ref": "Channel", + // "parameterName": "resource" + // }, + // "response": { + // "$ref": "Channel" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user", + // "https://www.googleapis.com/auth/admin.directory.user.readonly" + // ], + // "supportsSubscription": true + // } + +} + +// method id "directory.users.aliases.delete": + +type UsersAliasesDeleteCall struct { + s *Service + userKey string + alias string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Remove a alias for the user +func (r *UsersAliasesService) Delete(userKey string, alias string) *UsersAliasesDeleteCall { + c := &UsersAliasesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + c.alias = alias + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersAliasesDeleteCall) Fields(s ...googleapi.Field) *UsersAliasesDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersAliasesDeleteCall) Context(ctx context.Context) *UsersAliasesDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersAliasesDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersAliasesDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/aliases/{alias}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + "alias": c.alias, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.aliases.delete" call. +func (c *UsersAliasesDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Remove a alias for the user", + // "httpMethod": "DELETE", + // "id": "directory.users.aliases.delete", + // "parameterOrder": [ + // "userKey", + // "alias" + // ], + // "parameters": { + // "alias": { + // "description": "The alias to be removed", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "userKey": { + // "description": "Email or immutable ID of the user", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/aliases/{alias}", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user", + // "https://www.googleapis.com/auth/admin.directory.user.alias" + // ] + // } + +} + +// method id "directory.users.aliases.insert": + +type UsersAliasesInsertCall struct { + s *Service + userKey string + alias *Alias + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Add a alias for the user +func (r *UsersAliasesService) Insert(userKey string, alias *Alias) *UsersAliasesInsertCall { + c := &UsersAliasesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + c.alias = alias + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersAliasesInsertCall) Fields(s ...googleapi.Field) *UsersAliasesInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersAliasesInsertCall) Context(ctx context.Context) *UsersAliasesInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersAliasesInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersAliasesInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.alias) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/aliases") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.aliases.insert" call. +// Exactly one of *Alias or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Alias.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *UsersAliasesInsertCall) Do(opts ...googleapi.CallOption) (*Alias, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Alias{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Add a alias for the user", + // "httpMethod": "POST", + // "id": "directory.users.aliases.insert", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Email or immutable ID of the user", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/aliases", + // "request": { + // "$ref": "Alias" + // }, + // "response": { + // "$ref": "Alias" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user", + // "https://www.googleapis.com/auth/admin.directory.user.alias" + // ] + // } + +} + +// method id "directory.users.aliases.list": + +type UsersAliasesListCall struct { + s *Service + userKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: List all aliases for a user +func (r *UsersAliasesService) List(userKey string) *UsersAliasesListCall { + c := &UsersAliasesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + return c +} + +// Event sets the optional parameter "event": Event on which +// subscription is intended (if subscribing) +// +// Possible values: +// "add" - Alias Created Event +// "delete" - Alias Deleted Event +func (c *UsersAliasesListCall) Event(event string) *UsersAliasesListCall { + c.urlParams_.Set("event", event) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersAliasesListCall) Fields(s ...googleapi.Field) *UsersAliasesListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *UsersAliasesListCall) IfNoneMatch(entityTag string) *UsersAliasesListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersAliasesListCall) Context(ctx context.Context) *UsersAliasesListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersAliasesListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersAliasesListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/aliases") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.aliases.list" call. +// Exactly one of *Aliases or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Aliases.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *UsersAliasesListCall) Do(opts ...googleapi.CallOption) (*Aliases, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Aliases{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "List all aliases for a user", + // "httpMethod": "GET", + // "id": "directory.users.aliases.list", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "event": { + // "description": "Event on which subscription is intended (if subscribing)", + // "enum": [ + // "add", + // "delete" + // ], + // "enumDescriptions": [ + // "Alias Created Event", + // "Alias Deleted Event" + // ], + // "location": "query", + // "type": "string" + // }, + // "userKey": { + // "description": "Email or immutable ID of the user", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/aliases", + // "response": { + // "$ref": "Aliases" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user", + // "https://www.googleapis.com/auth/admin.directory.user.alias", + // "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", + // "https://www.googleapis.com/auth/admin.directory.user.readonly" + // ], + // "supportsSubscription": true + // } + +} + +// method id "directory.users.aliases.watch": + +type UsersAliasesWatchCall struct { + s *Service + userKey string + channel *Channel + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Watch: Watch for changes in user aliases list +func (r *UsersAliasesService) Watch(userKey string, channel *Channel) *UsersAliasesWatchCall { + c := &UsersAliasesWatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + c.channel = channel + return c +} + +// Event sets the optional parameter "event": Event on which +// subscription is intended (if subscribing) +// +// Possible values: +// "add" - Alias Created Event +// "delete" - Alias Deleted Event +func (c *UsersAliasesWatchCall) Event(event string) *UsersAliasesWatchCall { + c.urlParams_.Set("event", event) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersAliasesWatchCall) Fields(s ...googleapi.Field) *UsersAliasesWatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersAliasesWatchCall) Context(ctx context.Context) *UsersAliasesWatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersAliasesWatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersAliasesWatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.channel) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/aliases/watch") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.aliases.watch" call. +// Exactly one of *Channel or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Channel.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *UsersAliasesWatchCall) Do(opts ...googleapi.CallOption) (*Channel, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Channel{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Watch for changes in user aliases list", + // "httpMethod": "POST", + // "id": "directory.users.aliases.watch", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "event": { + // "description": "Event on which subscription is intended (if subscribing)", + // "enum": [ + // "add", + // "delete" + // ], + // "enumDescriptions": [ + // "Alias Created Event", + // "Alias Deleted Event" + // ], + // "location": "query", + // "type": "string" + // }, + // "userKey": { + // "description": "Email or immutable ID of the user", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/aliases/watch", + // "request": { + // "$ref": "Channel", + // "parameterName": "resource" + // }, + // "response": { + // "$ref": "Channel" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user", + // "https://www.googleapis.com/auth/admin.directory.user.alias", + // "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", + // "https://www.googleapis.com/auth/admin.directory.user.readonly" + // ], + // "supportsSubscription": true + // } + +} + +// method id "directory.users.photos.delete": + +type UsersPhotosDeleteCall struct { + s *Service + userKey string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Remove photos for the user +func (r *UsersPhotosService) Delete(userKey string) *UsersPhotosDeleteCall { + c := &UsersPhotosDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersPhotosDeleteCall) Fields(s ...googleapi.Field) *UsersPhotosDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersPhotosDeleteCall) Context(ctx context.Context) *UsersPhotosDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersPhotosDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersPhotosDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/photos/thumbnail") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.photos.delete" call. +func (c *UsersPhotosDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Remove photos for the user", + // "httpMethod": "DELETE", + // "id": "directory.users.photos.delete", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Email or immutable ID of the user", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/photos/thumbnail", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user" + // ] + // } + +} + +// method id "directory.users.photos.get": + +type UsersPhotosGetCall struct { + s *Service + userKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Retrieve photo of a user +func (r *UsersPhotosService) Get(userKey string) *UsersPhotosGetCall { + c := &UsersPhotosGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersPhotosGetCall) Fields(s ...googleapi.Field) *UsersPhotosGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *UsersPhotosGetCall) IfNoneMatch(entityTag string) *UsersPhotosGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersPhotosGetCall) Context(ctx context.Context) *UsersPhotosGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersPhotosGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersPhotosGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/photos/thumbnail") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.photos.get" call. +// Exactly one of *UserPhoto or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *UserPhoto.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *UsersPhotosGetCall) Do(opts ...googleapi.CallOption) (*UserPhoto, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &UserPhoto{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieve photo of a user", + // "httpMethod": "GET", + // "id": "directory.users.photos.get", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Email or immutable ID of the user", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/photos/thumbnail", + // "response": { + // "$ref": "UserPhoto" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user", + // "https://www.googleapis.com/auth/admin.directory.user.readonly" + // ] + // } + +} + +// method id "directory.users.photos.patch": + +type UsersPhotosPatchCall struct { + s *Service + userKey string + userphoto *UserPhoto + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Add a photo for the user. This method supports patch +// semantics. +func (r *UsersPhotosService) Patch(userKey string, userphoto *UserPhoto) *UsersPhotosPatchCall { + c := &UsersPhotosPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + c.userphoto = userphoto + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersPhotosPatchCall) Fields(s ...googleapi.Field) *UsersPhotosPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersPhotosPatchCall) Context(ctx context.Context) *UsersPhotosPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersPhotosPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersPhotosPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.userphoto) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/photos/thumbnail") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.photos.patch" call. +// Exactly one of *UserPhoto or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *UserPhoto.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *UsersPhotosPatchCall) Do(opts ...googleapi.CallOption) (*UserPhoto, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &UserPhoto{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Add a photo for the user. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "directory.users.photos.patch", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Email or immutable ID of the user", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/photos/thumbnail", + // "request": { + // "$ref": "UserPhoto" + // }, + // "response": { + // "$ref": "UserPhoto" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user" + // ] + // } + +} + +// method id "directory.users.photos.update": + +type UsersPhotosUpdateCall struct { + s *Service + userKey string + userphoto *UserPhoto + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Add a photo for the user +func (r *UsersPhotosService) Update(userKey string, userphoto *UserPhoto) *UsersPhotosUpdateCall { + c := &UsersPhotosUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + c.userphoto = userphoto + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *UsersPhotosUpdateCall) Fields(s ...googleapi.Field) *UsersPhotosUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *UsersPhotosUpdateCall) Context(ctx context.Context) *UsersPhotosUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *UsersPhotosUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *UsersPhotosUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.userphoto) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/photos/thumbnail") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PUT", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.users.photos.update" call. +// Exactly one of *UserPhoto or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *UserPhoto.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *UsersPhotosUpdateCall) Do(opts ...googleapi.CallOption) (*UserPhoto, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &UserPhoto{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Add a photo for the user", + // "httpMethod": "PUT", + // "id": "directory.users.photos.update", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Email or immutable ID of the user", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/photos/thumbnail", + // "request": { + // "$ref": "UserPhoto" + // }, + // "response": { + // "$ref": "UserPhoto" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user" + // ] + // } + +} + +// method id "directory.verificationCodes.generate": + +type VerificationCodesGenerateCall struct { + s *Service + userKey string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Generate: Generate new backup verification codes for the user. +func (r *VerificationCodesService) Generate(userKey string) *VerificationCodesGenerateCall { + c := &VerificationCodesGenerateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *VerificationCodesGenerateCall) Fields(s ...googleapi.Field) *VerificationCodesGenerateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *VerificationCodesGenerateCall) Context(ctx context.Context) *VerificationCodesGenerateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *VerificationCodesGenerateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *VerificationCodesGenerateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/verificationCodes/generate") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.verificationCodes.generate" call. +func (c *VerificationCodesGenerateCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Generate new backup verification codes for the user.", + // "httpMethod": "POST", + // "id": "directory.verificationCodes.generate", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Email or immutable ID of the user", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/verificationCodes/generate", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user.security" + // ] + // } + +} + +// method id "directory.verificationCodes.invalidate": + +type VerificationCodesInvalidateCall struct { + s *Service + userKey string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Invalidate: Invalidate the current backup verification codes for the +// user. +func (r *VerificationCodesService) Invalidate(userKey string) *VerificationCodesInvalidateCall { + c := &VerificationCodesInvalidateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *VerificationCodesInvalidateCall) Fields(s ...googleapi.Field) *VerificationCodesInvalidateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *VerificationCodesInvalidateCall) Context(ctx context.Context) *VerificationCodesInvalidateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *VerificationCodesInvalidateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *VerificationCodesInvalidateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/verificationCodes/invalidate") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.verificationCodes.invalidate" call. +func (c *VerificationCodesInvalidateCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Invalidate the current backup verification codes for the user.", + // "httpMethod": "POST", + // "id": "directory.verificationCodes.invalidate", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Email or immutable ID of the user", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/verificationCodes/invalidate", + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user.security" + // ] + // } + +} + +// method id "directory.verificationCodes.list": + +type VerificationCodesListCall struct { + s *Service + userKey string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Returns the current set of valid backup verification codes for +// the specified user. +func (r *VerificationCodesService) List(userKey string) *VerificationCodesListCall { + c := &VerificationCodesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.userKey = userKey + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *VerificationCodesListCall) Fields(s ...googleapi.Field) *VerificationCodesListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *VerificationCodesListCall) IfNoneMatch(entityTag string) *VerificationCodesListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *VerificationCodesListCall) Context(ctx context.Context) *VerificationCodesListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *VerificationCodesListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *VerificationCodesListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/verificationCodes") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "userKey": c.userKey, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "directory.verificationCodes.list" call. +// Exactly one of *VerificationCodes or error will be non-nil. Any +// non-2xx status code is an error. Response headers are in either +// *VerificationCodes.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *VerificationCodesListCall) Do(opts ...googleapi.CallOption) (*VerificationCodes, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &VerificationCodes{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Returns the current set of valid backup verification codes for the specified user.", + // "httpMethod": "GET", + // "id": "directory.verificationCodes.list", + // "parameterOrder": [ + // "userKey" + // ], + // "parameters": { + // "userKey": { + // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "users/{userKey}/verificationCodes", + // "response": { + // "$ref": "VerificationCodes" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/admin.directory.user.security" + // ] + // } + +} diff --git a/vendor/google.golang.org/api/gensupport/buffer.go b/vendor/google.golang.org/api/gensupport/buffer.go new file mode 100644 index 00000000..3d0817ed --- /dev/null +++ b/vendor/google.golang.org/api/gensupport/buffer.go @@ -0,0 +1,79 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gensupport + +import ( + "bytes" + "io" + + "google.golang.org/api/googleapi" +) + +// MediaBuffer buffers data from an io.Reader to support uploading media in +// retryable chunks. It should be created with NewMediaBuffer. +type MediaBuffer struct { + media io.Reader + + chunk []byte // The current chunk which is pending upload. The capacity is the chunk size. + err error // Any error generated when populating chunk by reading media. + + // The absolute position of chunk in the underlying media. + off int64 +} + +// NewMediaBuffer initializes a MediaBuffer. +func NewMediaBuffer(media io.Reader, chunkSize int) *MediaBuffer { + return &MediaBuffer{media: media, chunk: make([]byte, 0, chunkSize)} +} + +// Chunk returns the current buffered chunk, the offset in the underlying media +// from which the chunk is drawn, and the size of the chunk. +// Successive calls to Chunk return the same chunk between calls to Next. +func (mb *MediaBuffer) Chunk() (chunk io.Reader, off int64, size int, err error) { + // There may already be data in chunk if Next has not been called since the previous call to Chunk. + if mb.err == nil && len(mb.chunk) == 0 { + mb.err = mb.loadChunk() + } + return bytes.NewReader(mb.chunk), mb.off, len(mb.chunk), mb.err +} + +// loadChunk will read from media into chunk, up to the capacity of chunk. +func (mb *MediaBuffer) loadChunk() error { + bufSize := cap(mb.chunk) + mb.chunk = mb.chunk[:bufSize] + + read := 0 + var err error + for err == nil && read < bufSize { + var n int + n, err = mb.media.Read(mb.chunk[read:]) + read += n + } + mb.chunk = mb.chunk[:read] + return err +} + +// Next advances to the next chunk, which will be returned by the next call to Chunk. +// Calls to Next without a corresponding prior call to Chunk will have no effect. +func (mb *MediaBuffer) Next() { + mb.off += int64(len(mb.chunk)) + mb.chunk = mb.chunk[0:0] +} + +type readerTyper struct { + io.Reader + googleapi.ContentTyper +} + +// ReaderAtToReader adapts a ReaderAt to be used as a Reader. +// If ra implements googleapi.ContentTyper, then the returned reader +// will also implement googleapi.ContentTyper, delegating to ra. +func ReaderAtToReader(ra io.ReaderAt, size int64) io.Reader { + r := io.NewSectionReader(ra, 0, size) + if typer, ok := ra.(googleapi.ContentTyper); ok { + return readerTyper{r, typer} + } + return r +} diff --git a/vendor/google.golang.org/api/gensupport/doc.go b/vendor/google.golang.org/api/gensupport/doc.go new file mode 100644 index 00000000..752c4b41 --- /dev/null +++ b/vendor/google.golang.org/api/gensupport/doc.go @@ -0,0 +1,10 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package gensupport is an internal implementation detail used by code +// generated by the google-api-go-generator tool. +// +// This package may be modified at any time without regard for backwards +// compatibility. It should not be used directly by API users. +package gensupport diff --git a/vendor/google.golang.org/api/gensupport/json.go b/vendor/google.golang.org/api/gensupport/json.go new file mode 100644 index 00000000..c01e3218 --- /dev/null +++ b/vendor/google.golang.org/api/gensupport/json.go @@ -0,0 +1,211 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gensupport + +import ( + "encoding/json" + "fmt" + "reflect" + "strings" +) + +// MarshalJSON returns a JSON encoding of schema containing only selected fields. +// A field is selected if any of the following is true: +// * it has a non-empty value +// * its field name is present in forceSendFields and it is not a nil pointer or nil interface +// * its field name is present in nullFields. +// The JSON key for each selected field is taken from the field's json: struct tag. +func MarshalJSON(schema interface{}, forceSendFields, nullFields []string) ([]byte, error) { + if len(forceSendFields) == 0 && len(nullFields) == 0 { + return json.Marshal(schema) + } + + mustInclude := make(map[string]bool) + for _, f := range forceSendFields { + mustInclude[f] = true + } + useNull := make(map[string]bool) + useNullMaps := make(map[string]map[string]bool) + for _, nf := range nullFields { + parts := strings.SplitN(nf, ".", 2) + field := parts[0] + if len(parts) == 1 { + useNull[field] = true + } else { + if useNullMaps[field] == nil { + useNullMaps[field] = map[string]bool{} + } + useNullMaps[field][parts[1]] = true + } + } + + dataMap, err := schemaToMap(schema, mustInclude, useNull, useNullMaps) + if err != nil { + return nil, err + } + return json.Marshal(dataMap) +} + +func schemaToMap(schema interface{}, mustInclude, useNull map[string]bool, useNullMaps map[string]map[string]bool) (map[string]interface{}, error) { + m := make(map[string]interface{}) + s := reflect.ValueOf(schema) + st := s.Type() + + for i := 0; i < s.NumField(); i++ { + jsonTag := st.Field(i).Tag.Get("json") + if jsonTag == "" { + continue + } + tag, err := parseJSONTag(jsonTag) + if err != nil { + return nil, err + } + if tag.ignore { + continue + } + + v := s.Field(i) + f := st.Field(i) + + if useNull[f.Name] { + if !isEmptyValue(v) { + return nil, fmt.Errorf("field %q in NullFields has non-empty value", f.Name) + } + m[tag.apiName] = nil + continue + } + + if !includeField(v, f, mustInclude) { + continue + } + + // If map fields are explicitly set to null, use a map[string]interface{}. + if f.Type.Kind() == reflect.Map && useNullMaps[f.Name] != nil { + ms, ok := v.Interface().(map[string]string) + if !ok { + return nil, fmt.Errorf("field %q has keys in NullFields but is not a map[string]string", f.Name) + } + mi := map[string]interface{}{} + for k, v := range ms { + mi[k] = v + } + for k := range useNullMaps[f.Name] { + mi[k] = nil + } + m[tag.apiName] = mi + continue + } + + // nil maps are treated as empty maps. + if f.Type.Kind() == reflect.Map && v.IsNil() { + m[tag.apiName] = map[string]string{} + continue + } + + // nil slices are treated as empty slices. + if f.Type.Kind() == reflect.Slice && v.IsNil() { + m[tag.apiName] = []bool{} + continue + } + + if tag.stringFormat { + m[tag.apiName] = formatAsString(v, f.Type.Kind()) + } else { + m[tag.apiName] = v.Interface() + } + } + return m, nil +} + +// formatAsString returns a string representation of v, dereferencing it first if possible. +func formatAsString(v reflect.Value, kind reflect.Kind) string { + if kind == reflect.Ptr && !v.IsNil() { + v = v.Elem() + } + + return fmt.Sprintf("%v", v.Interface()) +} + +// jsonTag represents a restricted version of the struct tag format used by encoding/json. +// It is used to describe the JSON encoding of fields in a Schema struct. +type jsonTag struct { + apiName string + stringFormat bool + ignore bool +} + +// parseJSONTag parses a restricted version of the struct tag format used by encoding/json. +// The format of the tag must match that generated by the Schema.writeSchemaStruct method +// in the api generator. +func parseJSONTag(val string) (jsonTag, error) { + if val == "-" { + return jsonTag{ignore: true}, nil + } + + var tag jsonTag + + i := strings.Index(val, ",") + if i == -1 || val[:i] == "" { + return tag, fmt.Errorf("malformed json tag: %s", val) + } + + tag = jsonTag{ + apiName: val[:i], + } + + switch val[i+1:] { + case "omitempty": + case "omitempty,string": + tag.stringFormat = true + default: + return tag, fmt.Errorf("malformed json tag: %s", val) + } + + return tag, nil +} + +// Reports whether the struct field "f" with value "v" should be included in JSON output. +func includeField(v reflect.Value, f reflect.StructField, mustInclude map[string]bool) bool { + // The regular JSON encoding of a nil pointer is "null", which means "delete this field". + // Therefore, we could enable field deletion by honoring pointer fields' presence in the mustInclude set. + // However, many fields are not pointers, so there would be no way to delete these fields. + // Rather than partially supporting field deletion, we ignore mustInclude for nil pointer fields. + // Deletion will be handled by a separate mechanism. + if f.Type.Kind() == reflect.Ptr && v.IsNil() { + return false + } + + // The "any" type is represented as an interface{}. If this interface + // is nil, there is no reasonable representation to send. We ignore + // these fields, for the same reasons as given above for pointers. + if f.Type.Kind() == reflect.Interface && v.IsNil() { + return false + } + + return mustInclude[f.Name] || !isEmptyValue(v) +} + +// isEmptyValue reports whether v is the empty value for its type. This +// implementation is based on that of the encoding/json package, but its +// correctness does not depend on it being identical. What's important is that +// this function return false in situations where v should not be sent as part +// of a PATCH operation. +func isEmptyValue(v reflect.Value) bool { + switch v.Kind() { + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + } + return false +} diff --git a/vendor/google.golang.org/api/gensupport/jsonfloat.go b/vendor/google.golang.org/api/gensupport/jsonfloat.go new file mode 100644 index 00000000..83778508 --- /dev/null +++ b/vendor/google.golang.org/api/gensupport/jsonfloat.go @@ -0,0 +1,57 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package gensupport + +import ( + "encoding/json" + "errors" + "fmt" + "math" +) + +// JSONFloat64 is a float64 that supports proper unmarshaling of special float +// values in JSON, according to +// https://developers.google.com/protocol-buffers/docs/proto3#json. Although +// that is a proto-to-JSON spec, it applies to all Google APIs. +// +// The jsonpb package +// (https://github.com/golang/protobuf/blob/master/jsonpb/jsonpb.go) has +// similar functionality, but only for direct translation from proto messages +// to JSON. +type JSONFloat64 float64 + +func (f *JSONFloat64) UnmarshalJSON(data []byte) error { + var ff float64 + if err := json.Unmarshal(data, &ff); err == nil { + *f = JSONFloat64(ff) + return nil + } + var s string + if err := json.Unmarshal(data, &s); err == nil { + switch s { + case "NaN": + ff = math.NaN() + case "Infinity": + ff = math.Inf(1) + case "-Infinity": + ff = math.Inf(-1) + default: + return fmt.Errorf("google.golang.org/api/internal: bad float string %q", s) + } + *f = JSONFloat64(ff) + return nil + } + return errors.New("google.golang.org/api/internal: data not float or string") +} diff --git a/vendor/google.golang.org/api/gensupport/media.go b/vendor/google.golang.org/api/gensupport/media.go new file mode 100644 index 00000000..0ef96b3f --- /dev/null +++ b/vendor/google.golang.org/api/gensupport/media.go @@ -0,0 +1,363 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gensupport + +import ( + "bytes" + "fmt" + "io" + "io/ioutil" + "mime" + "mime/multipart" + "net/http" + "net/textproto" + "strings" + "sync" + + "google.golang.org/api/googleapi" +) + +const sniffBuffSize = 512 + +func newContentSniffer(r io.Reader) *contentSniffer { + return &contentSniffer{r: r} +} + +// contentSniffer wraps a Reader, and reports the content type determined by sniffing up to 512 bytes from the Reader. +type contentSniffer struct { + r io.Reader + start []byte // buffer for the sniffed bytes. + err error // set to any error encountered while reading bytes to be sniffed. + + ctype string // set on first sniff. + sniffed bool // set to true on first sniff. +} + +func (cs *contentSniffer) Read(p []byte) (n int, err error) { + // Ensure that the content type is sniffed before any data is consumed from Reader. + _, _ = cs.ContentType() + + if len(cs.start) > 0 { + n := copy(p, cs.start) + cs.start = cs.start[n:] + return n, nil + } + + // We may have read some bytes into start while sniffing, even if the read ended in an error. + // We should first return those bytes, then the error. + if cs.err != nil { + return 0, cs.err + } + + // Now we have handled all bytes that were buffered while sniffing. Now just delegate to the underlying reader. + return cs.r.Read(p) +} + +// ContentType returns the sniffed content type, and whether the content type was succesfully sniffed. +func (cs *contentSniffer) ContentType() (string, bool) { + if cs.sniffed { + return cs.ctype, cs.ctype != "" + } + cs.sniffed = true + // If ReadAll hits EOF, it returns err==nil. + cs.start, cs.err = ioutil.ReadAll(io.LimitReader(cs.r, sniffBuffSize)) + + // Don't try to detect the content type based on possibly incomplete data. + if cs.err != nil { + return "", false + } + + cs.ctype = http.DetectContentType(cs.start) + return cs.ctype, true +} + +// DetermineContentType determines the content type of the supplied reader. +// If the content type is already known, it can be specified via ctype. +// Otherwise, the content of media will be sniffed to determine the content type. +// If media implements googleapi.ContentTyper (deprecated), this will be used +// instead of sniffing the content. +// After calling DetectContentType the caller must not perform further reads on +// media, but rather read from the Reader that is returned. +func DetermineContentType(media io.Reader, ctype string) (io.Reader, string) { + // Note: callers could avoid calling DetectContentType if ctype != "", + // but doing the check inside this function reduces the amount of + // generated code. + if ctype != "" { + return media, ctype + } + + // For backwards compatability, allow clients to set content + // type by providing a ContentTyper for media. + if typer, ok := media.(googleapi.ContentTyper); ok { + return media, typer.ContentType() + } + + sniffer := newContentSniffer(media) + if ctype, ok := sniffer.ContentType(); ok { + return sniffer, ctype + } + // If content type could not be sniffed, reads from sniffer will eventually fail with an error. + return sniffer, "" +} + +type typeReader struct { + io.Reader + typ string +} + +// multipartReader combines the contents of multiple readers to create a multipart/related HTTP body. +// Close must be called if reads from the multipartReader are abandoned before reaching EOF. +type multipartReader struct { + pr *io.PipeReader + ctype string + mu sync.Mutex + pipeOpen bool +} + +// boundary optionally specifies the MIME boundary +func newMultipartReader(parts []typeReader, boundary string) *multipartReader { + mp := &multipartReader{pipeOpen: true} + var pw *io.PipeWriter + mp.pr, pw = io.Pipe() + mpw := multipart.NewWriter(pw) + if boundary != "" { + mpw.SetBoundary(boundary) + } + mp.ctype = "multipart/related; boundary=" + mpw.Boundary() + go func() { + for _, part := range parts { + w, err := mpw.CreatePart(typeHeader(part.typ)) + if err != nil { + mpw.Close() + pw.CloseWithError(fmt.Errorf("googleapi: CreatePart failed: %v", err)) + return + } + _, err = io.Copy(w, part.Reader) + if err != nil { + mpw.Close() + pw.CloseWithError(fmt.Errorf("googleapi: Copy failed: %v", err)) + return + } + } + + mpw.Close() + pw.Close() + }() + return mp +} + +func (mp *multipartReader) Read(data []byte) (n int, err error) { + return mp.pr.Read(data) +} + +func (mp *multipartReader) Close() error { + mp.mu.Lock() + if !mp.pipeOpen { + mp.mu.Unlock() + return nil + } + mp.pipeOpen = false + mp.mu.Unlock() + return mp.pr.Close() +} + +// CombineBodyMedia combines a json body with media content to create a multipart/related HTTP body. +// It returns a ReadCloser containing the combined body, and the overall "multipart/related" content type, with random boundary. +// +// The caller must call Close on the returned ReadCloser if reads are abandoned before reaching EOF. +func CombineBodyMedia(body io.Reader, bodyContentType string, media io.Reader, mediaContentType string) (io.ReadCloser, string) { + return combineBodyMedia(body, bodyContentType, media, mediaContentType, "") +} + +// combineBodyMedia is CombineBodyMedia but with an optional mimeBoundary field. +func combineBodyMedia(body io.Reader, bodyContentType string, media io.Reader, mediaContentType, mimeBoundary string) (io.ReadCloser, string) { + mp := newMultipartReader([]typeReader{ + {body, bodyContentType}, + {media, mediaContentType}, + }, mimeBoundary) + return mp, mp.ctype +} + +func typeHeader(contentType string) textproto.MIMEHeader { + h := make(textproto.MIMEHeader) + if contentType != "" { + h.Set("Content-Type", contentType) + } + return h +} + +// PrepareUpload determines whether the data in the supplied reader should be +// uploaded in a single request, or in sequential chunks. +// chunkSize is the size of the chunk that media should be split into. +// +// If chunkSize is zero, media is returned as the first value, and the other +// two return values are nil, true. +// +// Otherwise, a MediaBuffer is returned, along with a bool indicating whether the +// contents of media fit in a single chunk. +// +// After PrepareUpload has been called, media should no longer be used: the +// media content should be accessed via one of the return values. +func PrepareUpload(media io.Reader, chunkSize int) (r io.Reader, mb *MediaBuffer, singleChunk bool) { + if chunkSize == 0 { // do not chunk + return media, nil, true + } + mb = NewMediaBuffer(media, chunkSize) + _, _, _, err := mb.Chunk() + // If err is io.EOF, we can upload this in a single request. Otherwise, err is + // either nil or a non-EOF error. If it is the latter, then the next call to + // mb.Chunk will return the same error. Returning a MediaBuffer ensures that this + // error will be handled at some point. + return nil, mb, err == io.EOF +} + +// MediaInfo holds information for media uploads. It is intended for use by generated +// code only. +type MediaInfo struct { + // At most one of Media and MediaBuffer will be set. + media io.Reader + buffer *MediaBuffer + singleChunk bool + mType string + size int64 // mediaSize, if known. Used only for calls to progressUpdater_. + progressUpdater googleapi.ProgressUpdater +} + +// NewInfoFromMedia should be invoked from the Media method of a call. It returns a +// MediaInfo populated with chunk size and content type, and a reader or MediaBuffer +// if needed. +func NewInfoFromMedia(r io.Reader, options []googleapi.MediaOption) *MediaInfo { + mi := &MediaInfo{} + opts := googleapi.ProcessMediaOptions(options) + if !opts.ForceEmptyContentType { + r, mi.mType = DetermineContentType(r, opts.ContentType) + } + mi.media, mi.buffer, mi.singleChunk = PrepareUpload(r, opts.ChunkSize) + return mi +} + +// NewInfoFromResumableMedia should be invoked from the ResumableMedia method of a +// call. It returns a MediaInfo using the given reader, size and media type. +func NewInfoFromResumableMedia(r io.ReaderAt, size int64, mediaType string) *MediaInfo { + rdr := ReaderAtToReader(r, size) + rdr, mType := DetermineContentType(rdr, mediaType) + return &MediaInfo{ + size: size, + mType: mType, + buffer: NewMediaBuffer(rdr, googleapi.DefaultUploadChunkSize), + media: nil, + singleChunk: false, + } +} + +// SetProgressUpdater sets the progress updater for the media info. +func (mi *MediaInfo) SetProgressUpdater(pu googleapi.ProgressUpdater) { + if mi != nil { + mi.progressUpdater = pu + } +} + +// UploadType determines the type of upload: a single request, or a resumable +// series of requests. +func (mi *MediaInfo) UploadType() string { + if mi.singleChunk { + return "multipart" + } + return "resumable" +} + +// UploadRequest sets up an HTTP request for media upload. It adds headers +// as necessary, and returns a replacement for the body and a function for http.Request.GetBody. +func (mi *MediaInfo) UploadRequest(reqHeaders http.Header, body io.Reader) (newBody io.Reader, getBody func() (io.ReadCloser, error), cleanup func()) { + cleanup = func() {} + if mi == nil { + return body, nil, cleanup + } + var media io.Reader + if mi.media != nil { + // This only happens when the caller has turned off chunking. In that + // case, we write all of media in a single non-retryable request. + media = mi.media + } else if mi.singleChunk { + // The data fits in a single chunk, which has now been read into the MediaBuffer. + // We obtain that chunk so we can write it in a single request. The request can + // be retried because the data is stored in the MediaBuffer. + media, _, _, _ = mi.buffer.Chunk() + } + if media != nil { + fb := readerFunc(body) + fm := readerFunc(media) + combined, ctype := CombineBodyMedia(body, "application/json", media, mi.mType) + if fb != nil && fm != nil { + getBody = func() (io.ReadCloser, error) { + rb := ioutil.NopCloser(fb()) + rm := ioutil.NopCloser(fm()) + var mimeBoundary string + if _, params, err := mime.ParseMediaType(ctype); err == nil { + mimeBoundary = params["boundary"] + } + r, _ := combineBodyMedia(rb, "application/json", rm, mi.mType, mimeBoundary) + return r, nil + } + } + cleanup = func() { combined.Close() } + reqHeaders.Set("Content-Type", ctype) + body = combined + } + if mi.buffer != nil && mi.mType != "" && !mi.singleChunk { + reqHeaders.Set("X-Upload-Content-Type", mi.mType) + } + return body, getBody, cleanup +} + +// readerFunc returns a function that always returns an io.Reader that has the same +// contents as r, provided that can be done without consuming r. Otherwise, it +// returns nil. +// See http.NewRequest (in net/http/request.go). +func readerFunc(r io.Reader) func() io.Reader { + switch r := r.(type) { + case *bytes.Buffer: + buf := r.Bytes() + return func() io.Reader { return bytes.NewReader(buf) } + case *bytes.Reader: + snapshot := *r + return func() io.Reader { r := snapshot; return &r } + case *strings.Reader: + snapshot := *r + return func() io.Reader { r := snapshot; return &r } + default: + return nil + } +} + +// ResumableUpload returns an appropriately configured ResumableUpload value if the +// upload is resumable, or nil otherwise. +func (mi *MediaInfo) ResumableUpload(locURI string) *ResumableUpload { + if mi == nil || mi.singleChunk { + return nil + } + return &ResumableUpload{ + URI: locURI, + Media: mi.buffer, + MediaType: mi.mType, + Callback: func(curr int64) { + if mi.progressUpdater != nil { + mi.progressUpdater(curr, mi.size) + } + }, + } +} + +// SetGetBody sets the GetBody field of req to f. This was once needed +// to gracefully support Go 1.7 and earlier which didn't have that +// field. +// +// Deprecated: the code generator no longer uses this as of +// 2019-02-19. Nothing else should be calling this anyway, but we +// won't delete this immediately; it will be deleted in as early as 6 +// months. +func SetGetBody(req *http.Request, f func() (io.ReadCloser, error)) { + req.GetBody = f +} diff --git a/vendor/google.golang.org/api/gensupport/params.go b/vendor/google.golang.org/api/gensupport/params.go new file mode 100644 index 00000000..0e878a42 --- /dev/null +++ b/vendor/google.golang.org/api/gensupport/params.go @@ -0,0 +1,51 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gensupport + +import ( + "net/url" + + "google.golang.org/api/googleapi" +) + +// URLParams is a simplified replacement for url.Values +// that safely builds up URL parameters for encoding. +type URLParams map[string][]string + +// Get returns the first value for the given key, or "". +func (u URLParams) Get(key string) string { + vs := u[key] + if len(vs) == 0 { + return "" + } + return vs[0] +} + +// Set sets the key to value. +// It replaces any existing values. +func (u URLParams) Set(key, value string) { + u[key] = []string{value} +} + +// SetMulti sets the key to an array of values. +// It replaces any existing values. +// Note that values must not be modified after calling SetMulti +// so the caller is responsible for making a copy if necessary. +func (u URLParams) SetMulti(key string, values []string) { + u[key] = values +} + +// Encode encodes the values into ``URL encoded'' form +// ("bar=baz&foo=quux") sorted by key. +func (u URLParams) Encode() string { + return url.Values(u).Encode() +} + +// SetOptions sets the URL params and any additional call options. +func SetOptions(u URLParams, opts ...googleapi.CallOption) { + for _, o := range opts { + u.Set(o.Get()) + } +} diff --git a/vendor/google.golang.org/api/gensupport/resumable.go b/vendor/google.golang.org/api/gensupport/resumable.go new file mode 100644 index 00000000..e67ccd9a --- /dev/null +++ b/vendor/google.golang.org/api/gensupport/resumable.go @@ -0,0 +1,241 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gensupport + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "sync" + "time" + + gax "github.com/googleapis/gax-go/v2" +) + +// Backoff is an interface around gax.Backoff's Pause method, allowing tests to provide their +// own implementation. +type Backoff interface { + Pause() time.Duration +} + +// These are declared as global variables so that tests can overwrite them. +var ( + retryDeadline = 32 * time.Second + backoff = func() Backoff { + return &gax.Backoff{Initial: 100 * time.Millisecond} + } +) + +const ( + // statusTooManyRequests is returned by the storage API if the + // per-project limits have been temporarily exceeded. The request + // should be retried. + // https://cloud.google.com/storage/docs/json_api/v1/status-codes#standardcodes + statusTooManyRequests = 429 +) + +// ResumableUpload is used by the generated APIs to provide resumable uploads. +// It is not used by developers directly. +type ResumableUpload struct { + Client *http.Client + // URI is the resumable resource destination provided by the server after specifying "&uploadType=resumable". + URI string + UserAgent string // User-Agent for header of the request + // Media is the object being uploaded. + Media *MediaBuffer + // MediaType defines the media type, e.g. "image/jpeg". + MediaType string + + mu sync.Mutex // guards progress + progress int64 // number of bytes uploaded so far + + // Callback is an optional function that will be periodically called with the cumulative number of bytes uploaded. + Callback func(int64) +} + +// Progress returns the number of bytes uploaded at this point. +func (rx *ResumableUpload) Progress() int64 { + rx.mu.Lock() + defer rx.mu.Unlock() + return rx.progress +} + +// doUploadRequest performs a single HTTP request to upload data. +// off specifies the offset in rx.Media from which data is drawn. +// size is the number of bytes in data. +// final specifies whether data is the final chunk to be uploaded. +func (rx *ResumableUpload) doUploadRequest(ctx context.Context, data io.Reader, off, size int64, final bool) (*http.Response, error) { + req, err := http.NewRequest("POST", rx.URI, data) + if err != nil { + return nil, err + } + + req.ContentLength = size + var contentRange string + if final { + if size == 0 { + contentRange = fmt.Sprintf("bytes */%v", off) + } else { + contentRange = fmt.Sprintf("bytes %v-%v/%v", off, off+size-1, off+size) + } + } else { + contentRange = fmt.Sprintf("bytes %v-%v/*", off, off+size-1) + } + req.Header.Set("Content-Range", contentRange) + req.Header.Set("Content-Type", rx.MediaType) + req.Header.Set("User-Agent", rx.UserAgent) + + // Google's upload endpoint uses status code 308 for a + // different purpose than the "308 Permanent Redirect" + // since-standardized in RFC 7238. Because of the conflict in + // semantics, Google added this new request header which + // causes it to not use "308" and instead reply with 200 OK + // and sets the upload-specific "X-HTTP-Status-Code-Override: + // 308" response header. + req.Header.Set("X-GUploader-No-308", "yes") + + return SendRequest(ctx, rx.Client, req) +} + +func statusResumeIncomplete(resp *http.Response) bool { + // This is how the server signals "status resume incomplete" + // when X-GUploader-No-308 is set to "yes": + return resp != nil && resp.Header.Get("X-Http-Status-Code-Override") == "308" +} + +// reportProgress calls a user-supplied callback to report upload progress. +// If old==updated, the callback is not called. +func (rx *ResumableUpload) reportProgress(old, updated int64) { + if updated-old == 0 { + return + } + rx.mu.Lock() + rx.progress = updated + rx.mu.Unlock() + if rx.Callback != nil { + rx.Callback(updated) + } +} + +// transferChunk performs a single HTTP request to upload a single chunk from rx.Media. +func (rx *ResumableUpload) transferChunk(ctx context.Context) (*http.Response, error) { + chunk, off, size, err := rx.Media.Chunk() + + done := err == io.EOF + if !done && err != nil { + return nil, err + } + + res, err := rx.doUploadRequest(ctx, chunk, off, int64(size), done) + if err != nil { + return res, err + } + + // We sent "X-GUploader-No-308: yes" (see comment elsewhere in + // this file), so we don't expect to get a 308. + if res.StatusCode == 308 { + return nil, errors.New("unexpected 308 response status code") + } + + if res.StatusCode == http.StatusOK { + rx.reportProgress(off, off+int64(size)) + } + + if statusResumeIncomplete(res) { + rx.Media.Next() + } + return res, nil +} + +// Upload starts the process of a resumable upload with a cancellable context. +// It retries using the provided back off strategy until cancelled or the +// strategy indicates to stop retrying. +// It is called from the auto-generated API code and is not visible to the user. +// Before sending an HTTP request, Upload calls any registered hook functions, +// and calls the returned functions after the request returns (see send.go). +// rx is private to the auto-generated API code. +// Exactly one of resp or err will be nil. If resp is non-nil, the caller must call resp.Body.Close. +func (rx *ResumableUpload) Upload(ctx context.Context) (resp *http.Response, err error) { + var shouldRetry = func(status int, err error) bool { + if 500 <= status && status <= 599 { + return true + } + if status == statusTooManyRequests { + return true + } + if err == io.ErrUnexpectedEOF { + return true + } + if err, ok := err.(interface{ Temporary() bool }); ok { + return err.Temporary() + } + return false + } + + // There are a couple of cases where it's possible for err and resp to both + // be non-nil. However, we expose a simpler contract to our callers: exactly + // one of resp and err will be non-nil. This means that any response body + // must be closed here before returning a non-nil error. + var prepareReturn = func(resp *http.Response, err error) (*http.Response, error) { + if err != nil { + if resp != nil && resp.Body != nil { + resp.Body.Close() + } + return nil, err + } + return resp, nil + } + + // Send all chunks. + for { + var pause time.Duration + + // Each chunk gets its own initialized-at-zero retry. + bo := backoff() + quitAfter := time.After(retryDeadline) + + // Retry loop for a single chunk. + for { + select { + case <-ctx.Done(): + if err == nil { + err = ctx.Err() + } + return prepareReturn(resp, err) + case <-time.After(pause): + case <-quitAfter: + return prepareReturn(resp, err) + } + + resp, err = rx.transferChunk(ctx) + + var status int + if resp != nil { + status = resp.StatusCode + } + + // Check if we should retry the request. + if !shouldRetry(status, err) { + break + } + + pause = bo.Pause() + if resp != nil && resp.Body != nil { + resp.Body.Close() + } + } + + // If the chunk was uploaded successfully, but there's still + // more to go, upload the next chunk without any delay. + if statusResumeIncomplete(resp) { + resp.Body.Close() + continue + } + + return prepareReturn(resp, err) + } +} diff --git a/vendor/google.golang.org/api/gensupport/send.go b/vendor/google.golang.org/api/gensupport/send.go new file mode 100644 index 00000000..57993930 --- /dev/null +++ b/vendor/google.golang.org/api/gensupport/send.go @@ -0,0 +1,87 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gensupport + +import ( + "context" + "encoding/json" + "errors" + "net/http" +) + +// Hook is the type of a function that is called once before each HTTP request +// that is sent by a generated API. It returns a function that is called after +// the request returns. +// Hooks are not called if the context is nil. +type Hook func(ctx context.Context, req *http.Request) func(resp *http.Response) + +var hooks []Hook + +// RegisterHook registers a Hook to be called before each HTTP request by a +// generated API. Hooks are called in the order they are registered. Each +// hook can return a function; if it is non-nil, it is called after the HTTP +// request returns. These functions are called in the reverse order. +// RegisterHook should not be called concurrently with itself or SendRequest. +func RegisterHook(h Hook) { + hooks = append(hooks, h) +} + +// SendRequest sends a single HTTP request using the given client. +// If ctx is non-nil, it calls all hooks, then sends the request with +// req.WithContext, then calls any functions returned by the hooks in +// reverse order. +func SendRequest(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { + // Disallow Accept-Encoding because it interferes with the automatic gzip handling + // done by the default http.Transport. See https://github.com/google/google-api-go-client/issues/219. + if _, ok := req.Header["Accept-Encoding"]; ok { + return nil, errors.New("google api: custom Accept-Encoding headers not allowed") + } + if ctx == nil { + return client.Do(req) + } + // Call hooks in order of registration, store returned funcs. + post := make([]func(resp *http.Response), len(hooks)) + for i, h := range hooks { + fn := h(ctx, req) + post[i] = fn + } + + // Send request. + resp, err := send(ctx, client, req) + + // Call returned funcs in reverse order. + for i := len(post) - 1; i >= 0; i-- { + if fn := post[i]; fn != nil { + fn(resp) + } + } + return resp, err +} + +func send(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { + if client == nil { + client = http.DefaultClient + } + resp, err := client.Do(req.WithContext(ctx)) + // If we got an error, and the context has been canceled, + // the context's error is probably more useful. + if err != nil { + select { + case <-ctx.Done(): + err = ctx.Err() + default: + } + } + return resp, err +} + +// DecodeResponse decodes the body of res into target. If there is no body, +// target is unchanged. +func DecodeResponse(target interface{}, res *http.Response) error { + if res.StatusCode == http.StatusNoContent { + return nil + } + return json.NewDecoder(res.Body).Decode(target) +} diff --git a/vendor/google.golang.org/api/googleapi/googleapi.go b/vendor/google.golang.org/api/googleapi/googleapi.go new file mode 100644 index 00000000..ab537676 --- /dev/null +++ b/vendor/google.golang.org/api/googleapi/googleapi.go @@ -0,0 +1,403 @@ +// Copyright 2011 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package googleapi contains the common code shared by all Google API +// libraries. +package googleapi // import "google.golang.org/api/googleapi" + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "net/http" + "net/url" + "strings" + + "google.golang.org/api/googleapi/internal/uritemplates" +) + +// ContentTyper is an interface for Readers which know (or would like +// to override) their Content-Type. If a media body doesn't implement +// ContentTyper, the type is sniffed from the content using +// http.DetectContentType. +type ContentTyper interface { + ContentType() string +} + +// A SizeReaderAt is a ReaderAt with a Size method. +// An io.SectionReader implements SizeReaderAt. +type SizeReaderAt interface { + io.ReaderAt + Size() int64 +} + +// ServerResponse is embedded in each Do response and +// provides the HTTP status code and header sent by the server. +type ServerResponse struct { + // HTTPStatusCode is the server's response status code. When using a + // resource method's Do call, this will always be in the 2xx range. + HTTPStatusCode int + // Header contains the response header fields from the server. + Header http.Header +} + +const ( + // Version defines the gax version being used. This is typically sent + // in an HTTP header to services. + Version = "0.5" + + // UserAgent is the header string used to identify this package. + UserAgent = "google-api-go-client/" + Version + + // DefaultUploadChunkSize is the default chunk size to use for resumable + // uploads if not specified by the user. + DefaultUploadChunkSize = 8 * 1024 * 1024 + + // MinUploadChunkSize is the minimum chunk size that can be used for + // resumable uploads. All user-specified chunk sizes must be multiple of + // this value. + MinUploadChunkSize = 256 * 1024 +) + +// Error contains an error response from the server. +type Error struct { + // Code is the HTTP response status code and will always be populated. + Code int `json:"code"` + // Message is the server response message and is only populated when + // explicitly referenced by the JSON server response. + Message string `json:"message"` + // Body is the raw response returned by the server. + // It is often but not always JSON, depending on how the request fails. + Body string + // Header contains the response header fields from the server. + Header http.Header + + Errors []ErrorItem +} + +// ErrorItem is a detailed error code & message from the Google API frontend. +type ErrorItem struct { + // Reason is the typed error code. For example: "some_example". + Reason string `json:"reason"` + // Message is the human-readable description of the error. + Message string `json:"message"` +} + +func (e *Error) Error() string { + if len(e.Errors) == 0 && e.Message == "" { + return fmt.Sprintf("googleapi: got HTTP response code %d with body: %v", e.Code, e.Body) + } + var buf bytes.Buffer + fmt.Fprintf(&buf, "googleapi: Error %d: ", e.Code) + if e.Message != "" { + fmt.Fprintf(&buf, "%s", e.Message) + } + if len(e.Errors) == 0 { + return strings.TrimSpace(buf.String()) + } + if len(e.Errors) == 1 && e.Errors[0].Message == e.Message { + fmt.Fprintf(&buf, ", %s", e.Errors[0].Reason) + return buf.String() + } + fmt.Fprintln(&buf, "\nMore details:") + for _, v := range e.Errors { + fmt.Fprintf(&buf, "Reason: %s, Message: %s\n", v.Reason, v.Message) + } + return buf.String() +} + +type errorReply struct { + Error *Error `json:"error"` +} + +// CheckResponse returns an error (of type *Error) if the response +// status code is not 2xx. +func CheckResponse(res *http.Response) error { + if res.StatusCode >= 200 && res.StatusCode <= 299 { + return nil + } + slurp, err := ioutil.ReadAll(res.Body) + if err == nil { + jerr := new(errorReply) + err = json.Unmarshal(slurp, jerr) + if err == nil && jerr.Error != nil { + if jerr.Error.Code == 0 { + jerr.Error.Code = res.StatusCode + } + jerr.Error.Body = string(slurp) + return jerr.Error + } + } + return &Error{ + Code: res.StatusCode, + Body: string(slurp), + Header: res.Header, + } +} + +// IsNotModified reports whether err is the result of the +// server replying with http.StatusNotModified. +// Such error values are sometimes returned by "Do" methods +// on calls when If-None-Match is used. +func IsNotModified(err error) bool { + if err == nil { + return false + } + ae, ok := err.(*Error) + return ok && ae.Code == http.StatusNotModified +} + +// CheckMediaResponse returns an error (of type *Error) if the response +// status code is not 2xx. Unlike CheckResponse it does not assume the +// body is a JSON error document. +// It is the caller's responsibility to close res.Body. +func CheckMediaResponse(res *http.Response) error { + if res.StatusCode >= 200 && res.StatusCode <= 299 { + return nil + } + slurp, _ := ioutil.ReadAll(io.LimitReader(res.Body, 1<<20)) + return &Error{ + Code: res.StatusCode, + Body: string(slurp), + } +} + +// MarshalStyle defines whether to marshal JSON with a {"data": ...} wrapper. +type MarshalStyle bool + +// WithDataWrapper marshals JSON with a {"data": ...} wrapper. +var WithDataWrapper = MarshalStyle(true) + +// WithoutDataWrapper marshals JSON without a {"data": ...} wrapper. +var WithoutDataWrapper = MarshalStyle(false) + +func (wrap MarshalStyle) JSONReader(v interface{}) (io.Reader, error) { + buf := new(bytes.Buffer) + if wrap { + buf.Write([]byte(`{"data": `)) + } + err := json.NewEncoder(buf).Encode(v) + if err != nil { + return nil, err + } + if wrap { + buf.Write([]byte(`}`)) + } + return buf, nil +} + +// ProgressUpdater is a function that is called upon every progress update of a resumable upload. +// This is the only part of a resumable upload (from googleapi) that is usable by the developer. +// The remaining usable pieces of resumable uploads is exposed in each auto-generated API. +type ProgressUpdater func(current, total int64) + +// MediaOption defines the interface for setting media options. +type MediaOption interface { + setOptions(o *MediaOptions) +} + +type contentTypeOption string + +func (ct contentTypeOption) setOptions(o *MediaOptions) { + o.ContentType = string(ct) + if o.ContentType == "" { + o.ForceEmptyContentType = true + } +} + +// ContentType returns a MediaOption which sets the Content-Type header for media uploads. +// If ctype is empty, the Content-Type header will be omitted. +func ContentType(ctype string) MediaOption { + return contentTypeOption(ctype) +} + +type chunkSizeOption int + +func (cs chunkSizeOption) setOptions(o *MediaOptions) { + size := int(cs) + if size%MinUploadChunkSize != 0 { + size += MinUploadChunkSize - (size % MinUploadChunkSize) + } + o.ChunkSize = size +} + +// ChunkSize returns a MediaOption which sets the chunk size for media uploads. +// size will be rounded up to the nearest multiple of 256K. +// Media which contains fewer than size bytes will be uploaded in a single request. +// Media which contains size bytes or more will be uploaded in separate chunks. +// If size is zero, media will be uploaded in a single request. +func ChunkSize(size int) MediaOption { + return chunkSizeOption(size) +} + +// MediaOptions stores options for customizing media upload. It is not used by developers directly. +type MediaOptions struct { + ContentType string + ForceEmptyContentType bool + + ChunkSize int +} + +// ProcessMediaOptions stores options from opts in a MediaOptions. +// It is not used by developers directly. +func ProcessMediaOptions(opts []MediaOption) *MediaOptions { + mo := &MediaOptions{ChunkSize: DefaultUploadChunkSize} + for _, o := range opts { + o.setOptions(mo) + } + return mo +} + +// ResolveRelative resolves relatives such as "http://www.golang.org/" and +// "topics/myproject/mytopic" into a single string, such as +// "http://www.golang.org/topics/myproject/mytopic". It strips all parent +// references (e.g. ../..) as well as anything after the host +// (e.g. /bar/gaz gets stripped out of foo.com/bar/gaz). +func ResolveRelative(basestr, relstr string) string { + u, _ := url.Parse(basestr) + afterColonPath := "" + if i := strings.IndexRune(relstr, ':'); i > 0 { + afterColonPath = relstr[i+1:] + relstr = relstr[:i] + } + rel, _ := url.Parse(relstr) + u = u.ResolveReference(rel) + us := u.String() + if afterColonPath != "" { + us = fmt.Sprintf("%s:%s", us, afterColonPath) + } + us = strings.Replace(us, "%7B", "{", -1) + us = strings.Replace(us, "%7D", "}", -1) + us = strings.Replace(us, "%2A", "*", -1) + return us +} + +// Expand subsitutes any {encoded} strings in the URL passed in using +// the map supplied. +// +// This calls SetOpaque to avoid encoding of the parameters in the URL path. +func Expand(u *url.URL, expansions map[string]string) { + escaped, unescaped, err := uritemplates.Expand(u.Path, expansions) + if err == nil { + u.Path = unescaped + u.RawPath = escaped + } +} + +// CloseBody is used to close res.Body. +// Prior to calling Close, it also tries to Read a small amount to see an EOF. +// Not seeing an EOF can prevent HTTP Transports from reusing connections. +func CloseBody(res *http.Response) { + if res == nil || res.Body == nil { + return + } + // Justification for 3 byte reads: two for up to "\r\n" after + // a JSON/XML document, and then 1 to see EOF if we haven't yet. + // TODO(bradfitz): detect Go 1.3+ and skip these reads. + // See https://codereview.appspot.com/58240043 + // and https://codereview.appspot.com/49570044 + buf := make([]byte, 1) + for i := 0; i < 3; i++ { + _, err := res.Body.Read(buf) + if err != nil { + break + } + } + res.Body.Close() + +} + +// VariantType returns the type name of the given variant. +// If the map doesn't contain the named key or the value is not a []interface{}, "" is returned. +// This is used to support "variant" APIs that can return one of a number of different types. +func VariantType(t map[string]interface{}) string { + s, _ := t["type"].(string) + return s +} + +// ConvertVariant uses the JSON encoder/decoder to fill in the struct 'dst' with the fields found in variant 'v'. +// This is used to support "variant" APIs that can return one of a number of different types. +// It reports whether the conversion was successful. +func ConvertVariant(v map[string]interface{}, dst interface{}) bool { + var buf bytes.Buffer + err := json.NewEncoder(&buf).Encode(v) + if err != nil { + return false + } + return json.Unmarshal(buf.Bytes(), dst) == nil +} + +// A Field names a field to be retrieved with a partial response. +// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// +// Partial responses can dramatically reduce the amount of data that must be sent to your application. +// In order to request partial responses, you can specify the full list of fields +// that your application needs by adding the Fields option to your request. +// +// Field strings use camelCase with leading lower-case characters to identify fields within the response. +// +// For example, if your response has a "NextPageToken" and a slice of "Items" with "Id" fields, +// you could request just those fields like this: +// +// svc.Events.List().Fields("nextPageToken", "items/id").Do() +// +// or if you were also interested in each Item's "Updated" field, you can combine them like this: +// +// svc.Events.List().Fields("nextPageToken", "items(id,updated)").Do() +// +// More information about field formatting can be found here: +// https://developers.google.com/+/api/#fields-syntax +// +// Another way to find field names is through the Google API explorer: +// https://developers.google.com/apis-explorer/#p/ +type Field string + +// CombineFields combines fields into a single string. +func CombineFields(s []Field) string { + r := make([]string, len(s)) + for i, v := range s { + r[i] = string(v) + } + return strings.Join(r, ",") +} + +// A CallOption is an optional argument to an API call. +// It should be treated as an opaque value by users of Google APIs. +// +// A CallOption is something that configures an API call in a way that is +// not specific to that API; for instance, controlling the quota user for +// an API call is common across many APIs, and is thus a CallOption. +type CallOption interface { + Get() (key, value string) +} + +// QuotaUser returns a CallOption that will set the quota user for a call. +// The quota user can be used by server-side applications to control accounting. +// It can be an arbitrary string up to 40 characters, and will override UserIP +// if both are provided. +func QuotaUser(u string) CallOption { return quotaUser(u) } + +type quotaUser string + +func (q quotaUser) Get() (string, string) { return "quotaUser", string(q) } + +// UserIP returns a CallOption that will set the "userIp" parameter of a call. +// This should be the IP address of the originating request. +func UserIP(ip string) CallOption { return userIP(ip) } + +type userIP string + +func (i userIP) Get() (string, string) { return "userIp", string(i) } + +// Trace returns a CallOption that enables diagnostic tracing for a call. +// traceToken is an ID supplied by Google support. +func Trace(traceToken string) CallOption { return traceTok(traceToken) } + +type traceTok string + +func (t traceTok) Get() (string, string) { return "trace", "token:" + string(t) } + +// TODO: Fields too diff --git a/vendor/google.golang.org/api/googleapi/internal/uritemplates/LICENSE b/vendor/google.golang.org/api/googleapi/internal/uritemplates/LICENSE new file mode 100644 index 00000000..de9c88cb --- /dev/null +++ b/vendor/google.golang.org/api/googleapi/internal/uritemplates/LICENSE @@ -0,0 +1,18 @@ +Copyright (c) 2013 Joshua Tacoma + +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 to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/google.golang.org/api/googleapi/internal/uritemplates/uritemplates.go b/vendor/google.golang.org/api/googleapi/internal/uritemplates/uritemplates.go new file mode 100644 index 00000000..63bf0538 --- /dev/null +++ b/vendor/google.golang.org/api/googleapi/internal/uritemplates/uritemplates.go @@ -0,0 +1,248 @@ +// Copyright 2013 Joshua Tacoma. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package uritemplates is a level 3 implementation of RFC 6570 (URI +// Template, http://tools.ietf.org/html/rfc6570). +// uritemplates does not support composite values (in Go: slices or maps) +// and so does not qualify as a level 4 implementation. +package uritemplates + +import ( + "bytes" + "errors" + "regexp" + "strconv" + "strings" +) + +var ( + unreserved = regexp.MustCompile("[^A-Za-z0-9\\-._~]") + reserved = regexp.MustCompile("[^A-Za-z0-9\\-._~:/?#[\\]@!$&'()*+,;=]") + validname = regexp.MustCompile("^([A-Za-z0-9_\\.]|%[0-9A-Fa-f][0-9A-Fa-f])+$") + hex = []byte("0123456789ABCDEF") +) + +func pctEncode(src []byte) []byte { + dst := make([]byte, len(src)*3) + for i, b := range src { + buf := dst[i*3 : i*3+3] + buf[0] = 0x25 + buf[1] = hex[b/16] + buf[2] = hex[b%16] + } + return dst +} + +// pairWriter is a convenience struct which allows escaped and unescaped +// versions of the template to be written in parallel. +type pairWriter struct { + escaped, unescaped bytes.Buffer +} + +// Write writes the provided string directly without any escaping. +func (w *pairWriter) Write(s string) { + w.escaped.WriteString(s) + w.unescaped.WriteString(s) +} + +// Escape writes the provided string, escaping the string for the +// escaped output. +func (w *pairWriter) Escape(s string, allowReserved bool) { + w.unescaped.WriteString(s) + if allowReserved { + w.escaped.Write(reserved.ReplaceAllFunc([]byte(s), pctEncode)) + } else { + w.escaped.Write(unreserved.ReplaceAllFunc([]byte(s), pctEncode)) + } +} + +// Escaped returns the escaped string. +func (w *pairWriter) Escaped() string { + return w.escaped.String() +} + +// Unescaped returns the unescaped string. +func (w *pairWriter) Unescaped() string { + return w.unescaped.String() +} + +// A uriTemplate is a parsed representation of a URI template. +type uriTemplate struct { + raw string + parts []templatePart +} + +// parse parses a URI template string into a uriTemplate object. +func parse(rawTemplate string) (*uriTemplate, error) { + split := strings.Split(rawTemplate, "{") + parts := make([]templatePart, len(split)*2-1) + for i, s := range split { + if i == 0 { + if strings.Contains(s, "}") { + return nil, errors.New("unexpected }") + } + parts[i].raw = s + continue + } + subsplit := strings.Split(s, "}") + if len(subsplit) != 2 { + return nil, errors.New("malformed template") + } + expression := subsplit[0] + var err error + parts[i*2-1], err = parseExpression(expression) + if err != nil { + return nil, err + } + parts[i*2].raw = subsplit[1] + } + return &uriTemplate{ + raw: rawTemplate, + parts: parts, + }, nil +} + +type templatePart struct { + raw string + terms []templateTerm + first string + sep string + named bool + ifemp string + allowReserved bool +} + +type templateTerm struct { + name string + explode bool + truncate int +} + +func parseExpression(expression string) (result templatePart, err error) { + switch expression[0] { + case '+': + result.sep = "," + result.allowReserved = true + expression = expression[1:] + case '.': + result.first = "." + result.sep = "." + expression = expression[1:] + case '/': + result.first = "/" + result.sep = "/" + expression = expression[1:] + case ';': + result.first = ";" + result.sep = ";" + result.named = true + expression = expression[1:] + case '?': + result.first = "?" + result.sep = "&" + result.named = true + result.ifemp = "=" + expression = expression[1:] + case '&': + result.first = "&" + result.sep = "&" + result.named = true + result.ifemp = "=" + expression = expression[1:] + case '#': + result.first = "#" + result.sep = "," + result.allowReserved = true + expression = expression[1:] + default: + result.sep = "," + } + rawterms := strings.Split(expression, ",") + result.terms = make([]templateTerm, len(rawterms)) + for i, raw := range rawterms { + result.terms[i], err = parseTerm(raw) + if err != nil { + break + } + } + return result, err +} + +func parseTerm(term string) (result templateTerm, err error) { + // TODO(djd): Remove "*" suffix parsing once we check that no APIs have + // mistakenly used that attribute. + if strings.HasSuffix(term, "*") { + result.explode = true + term = term[:len(term)-1] + } + split := strings.Split(term, ":") + if len(split) == 1 { + result.name = term + } else if len(split) == 2 { + result.name = split[0] + var parsed int64 + parsed, err = strconv.ParseInt(split[1], 10, 0) + result.truncate = int(parsed) + } else { + err = errors.New("multiple colons in same term") + } + if !validname.MatchString(result.name) { + err = errors.New("not a valid name: " + result.name) + } + if result.explode && result.truncate > 0 { + err = errors.New("both explode and prefix modifers on same term") + } + return result, err +} + +// Expand expands a URI template with a set of values to produce the +// resultant URI. Two forms of the result are returned: one with all the +// elements escaped, and one with the elements unescaped. +func (t *uriTemplate) Expand(values map[string]string) (escaped, unescaped string) { + var w pairWriter + for _, p := range t.parts { + p.expand(&w, values) + } + return w.Escaped(), w.Unescaped() +} + +func (tp *templatePart) expand(w *pairWriter, values map[string]string) { + if len(tp.raw) > 0 { + w.Write(tp.raw) + return + } + var first = true + for _, term := range tp.terms { + value, exists := values[term.name] + if !exists { + continue + } + if first { + w.Write(tp.first) + first = false + } else { + w.Write(tp.sep) + } + tp.expandString(w, term, value) + } +} + +func (tp *templatePart) expandName(w *pairWriter, name string, empty bool) { + if tp.named { + w.Write(name) + if empty { + w.Write(tp.ifemp) + } else { + w.Write("=") + } + } +} + +func (tp *templatePart) expandString(w *pairWriter, t templateTerm, s string) { + if len(s) > t.truncate && t.truncate > 0 { + s = s[:t.truncate] + } + tp.expandName(w, t.name, len(s) == 0) + w.Escape(s, tp.allowReserved) +} diff --git a/vendor/google.golang.org/api/googleapi/internal/uritemplates/utils.go b/vendor/google.golang.org/api/googleapi/internal/uritemplates/utils.go new file mode 100644 index 00000000..2e70b815 --- /dev/null +++ b/vendor/google.golang.org/api/googleapi/internal/uritemplates/utils.go @@ -0,0 +1,17 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uritemplates + +// Expand parses then expands a URI template with a set of values to produce +// the resultant URI. Two forms of the result are returned: one with all the +// elements escaped, and one with the elements unescaped. +func Expand(path string, values map[string]string) (escaped, unescaped string, err error) { + template, err := parse(path) + if err != nil { + return "", "", err + } + escaped, unescaped = template.Expand(values) + return escaped, unescaped, nil +} diff --git a/vendor/google.golang.org/api/googleapi/transport/apikey.go b/vendor/google.golang.org/api/googleapi/transport/apikey.go new file mode 100644 index 00000000..eca1ea25 --- /dev/null +++ b/vendor/google.golang.org/api/googleapi/transport/apikey.go @@ -0,0 +1,38 @@ +// Copyright 2012 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package transport contains HTTP transports used to make +// authenticated API requests. +package transport + +import ( + "errors" + "net/http" +) + +// APIKey is an HTTP Transport which wraps an underlying transport and +// appends an API Key "key" parameter to the URL of outgoing requests. +type APIKey struct { + // Key is the API Key to set on requests. + Key string + + // Transport is the underlying HTTP transport. + // If nil, http.DefaultTransport is used. + Transport http.RoundTripper +} + +func (t *APIKey) RoundTrip(req *http.Request) (*http.Response, error) { + rt := t.Transport + if rt == nil { + rt = http.DefaultTransport + if rt == nil { + return nil, errors.New("googleapi/transport: no Transport specified or available") + } + } + newReq := *req + args := newReq.URL.Query() + args.Set("key", t.Key) + newReq.URL.RawQuery = args.Encode() + return rt.RoundTrip(&newReq) +} diff --git a/vendor/google.golang.org/api/googleapi/types.go b/vendor/google.golang.org/api/googleapi/types.go new file mode 100644 index 00000000..a280e302 --- /dev/null +++ b/vendor/google.golang.org/api/googleapi/types.go @@ -0,0 +1,202 @@ +// Copyright 2013 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package googleapi + +import ( + "encoding/json" + "errors" + "strconv" +) + +// Int64s is a slice of int64s that marshal as quoted strings in JSON. +type Int64s []int64 + +func (q *Int64s) UnmarshalJSON(raw []byte) error { + *q = (*q)[:0] + var ss []string + if err := json.Unmarshal(raw, &ss); err != nil { + return err + } + for _, s := range ss { + v, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return err + } + *q = append(*q, int64(v)) + } + return nil +} + +// Int32s is a slice of int32s that marshal as quoted strings in JSON. +type Int32s []int32 + +func (q *Int32s) UnmarshalJSON(raw []byte) error { + *q = (*q)[:0] + var ss []string + if err := json.Unmarshal(raw, &ss); err != nil { + return err + } + for _, s := range ss { + v, err := strconv.ParseInt(s, 10, 32) + if err != nil { + return err + } + *q = append(*q, int32(v)) + } + return nil +} + +// Uint64s is a slice of uint64s that marshal as quoted strings in JSON. +type Uint64s []uint64 + +func (q *Uint64s) UnmarshalJSON(raw []byte) error { + *q = (*q)[:0] + var ss []string + if err := json.Unmarshal(raw, &ss); err != nil { + return err + } + for _, s := range ss { + v, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return err + } + *q = append(*q, uint64(v)) + } + return nil +} + +// Uint32s is a slice of uint32s that marshal as quoted strings in JSON. +type Uint32s []uint32 + +func (q *Uint32s) UnmarshalJSON(raw []byte) error { + *q = (*q)[:0] + var ss []string + if err := json.Unmarshal(raw, &ss); err != nil { + return err + } + for _, s := range ss { + v, err := strconv.ParseUint(s, 10, 32) + if err != nil { + return err + } + *q = append(*q, uint32(v)) + } + return nil +} + +// Float64s is a slice of float64s that marshal as quoted strings in JSON. +type Float64s []float64 + +func (q *Float64s) UnmarshalJSON(raw []byte) error { + *q = (*q)[:0] + var ss []string + if err := json.Unmarshal(raw, &ss); err != nil { + return err + } + for _, s := range ss { + v, err := strconv.ParseFloat(s, 64) + if err != nil { + return err + } + *q = append(*q, float64(v)) + } + return nil +} + +func quotedList(n int, fn func(dst []byte, i int) []byte) ([]byte, error) { + dst := make([]byte, 0, 2+n*10) // somewhat arbitrary + dst = append(dst, '[') + for i := 0; i < n; i++ { + if i > 0 { + dst = append(dst, ',') + } + dst = append(dst, '"') + dst = fn(dst, i) + dst = append(dst, '"') + } + dst = append(dst, ']') + return dst, nil +} + +func (q Int64s) MarshalJSON() ([]byte, error) { + return quotedList(len(q), func(dst []byte, i int) []byte { + return strconv.AppendInt(dst, q[i], 10) + }) +} + +func (q Int32s) MarshalJSON() ([]byte, error) { + return quotedList(len(q), func(dst []byte, i int) []byte { + return strconv.AppendInt(dst, int64(q[i]), 10) + }) +} + +func (q Uint64s) MarshalJSON() ([]byte, error) { + return quotedList(len(q), func(dst []byte, i int) []byte { + return strconv.AppendUint(dst, q[i], 10) + }) +} + +func (q Uint32s) MarshalJSON() ([]byte, error) { + return quotedList(len(q), func(dst []byte, i int) []byte { + return strconv.AppendUint(dst, uint64(q[i]), 10) + }) +} + +func (q Float64s) MarshalJSON() ([]byte, error) { + return quotedList(len(q), func(dst []byte, i int) []byte { + return strconv.AppendFloat(dst, q[i], 'g', -1, 64) + }) +} + +// RawMessage is a raw encoded JSON value. +// It is identical to json.RawMessage, except it does not suffer from +// https://golang.org/issue/14493. +type RawMessage []byte + +// MarshalJSON returns m. +func (m RawMessage) MarshalJSON() ([]byte, error) { + return m, nil +} + +// UnmarshalJSON sets *m to a copy of data. +func (m *RawMessage) UnmarshalJSON(data []byte) error { + if m == nil { + return errors.New("googleapi.RawMessage: UnmarshalJSON on nil pointer") + } + *m = append((*m)[:0], data...) + return nil +} + +/* + * Helper routines for simplifying the creation of optional fields of basic type. + */ + +// Bool is a helper routine that allocates a new bool value +// to store v and returns a pointer to it. +func Bool(v bool) *bool { return &v } + +// Int32 is a helper routine that allocates a new int32 value +// to store v and returns a pointer to it. +func Int32(v int32) *int32 { return &v } + +// Int64 is a helper routine that allocates a new int64 value +// to store v and returns a pointer to it. +func Int64(v int64) *int64 { return &v } + +// Float64 is a helper routine that allocates a new float64 value +// to store v and returns a pointer to it. +func Float64(v float64) *float64 { return &v } + +// Uint32 is a helper routine that allocates a new uint32 value +// to store v and returns a pointer to it. +func Uint32(v uint32) *uint32 { return &v } + +// Uint64 is a helper routine that allocates a new uint64 value +// to store v and returns a pointer to it. +func Uint64(v uint64) *uint64 { return &v } + +// String is a helper routine that allocates a new string value +// to store v and returns a pointer to it. +func String(v string) *string { return &v } diff --git a/vendor/google.golang.org/api/internal/creds.go b/vendor/google.golang.org/api/internal/creds.go new file mode 100644 index 00000000..69b8659f --- /dev/null +++ b/vendor/google.golang.org/api/internal/creds.go @@ -0,0 +1,102 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package internal + +import ( + "context" + "encoding/json" + "fmt" + "io/ioutil" + + "golang.org/x/oauth2" + + "golang.org/x/oauth2/google" +) + +// Creds returns credential information obtained from DialSettings, or if none, then +// it returns default credential information. +func Creds(ctx context.Context, ds *DialSettings) (*google.Credentials, error) { + if ds.Credentials != nil { + return ds.Credentials, nil + } + if ds.CredentialsJSON != nil { + return credentialsFromJSON(ctx, ds.CredentialsJSON, ds.Endpoint, ds.Scopes, ds.Audiences) + } + if ds.CredentialsFile != "" { + data, err := ioutil.ReadFile(ds.CredentialsFile) + if err != nil { + return nil, fmt.Errorf("cannot read credentials file: %v", err) + } + return credentialsFromJSON(ctx, data, ds.Endpoint, ds.Scopes, ds.Audiences) + } + if ds.TokenSource != nil { + return &google.Credentials{TokenSource: ds.TokenSource}, nil + } + cred, err := google.FindDefaultCredentials(ctx, ds.Scopes...) + if err != nil { + return nil, err + } + if len(cred.JSON) > 0 { + return credentialsFromJSON(ctx, cred.JSON, ds.Endpoint, ds.Scopes, ds.Audiences) + } + // For GAE and GCE, the JSON is empty so return the default credentials directly. + return cred, nil +} + +// JSON key file type. +const ( + serviceAccountKey = "service_account" +) + +// credentialsFromJSON returns a google.Credentials based on the input. +// +// - If the JSON is a service account and no scopes provided, returns self-signed JWT auth flow +// - Otherwise, returns OAuth 2.0 flow. +func credentialsFromJSON(ctx context.Context, data []byte, endpoint string, scopes []string, audiences []string) (*google.Credentials, error) { + cred, err := google.CredentialsFromJSON(ctx, data, scopes...) + if err != nil { + return nil, err + } + if len(data) > 0 && len(scopes) == 0 { + var f struct { + Type string `json:"type"` + // The rest JSON fields are omitted because they are not used. + } + if err := json.Unmarshal(cred.JSON, &f); err != nil { + return nil, err + } + if f.Type == serviceAccountKey { + ts, err := selfSignedJWTTokenSource(data, endpoint, audiences) + if err != nil { + return nil, err + } + cred.TokenSource = ts + } + } + return cred, err +} + +func selfSignedJWTTokenSource(data []byte, endpoint string, audiences []string) (oauth2.TokenSource, error) { + // Use the API endpoint as the default audience + audience := endpoint + if len(audiences) > 0 { + // TODO(shinfan): Update golang oauth to support multiple audiences. + if len(audiences) > 1 { + return nil, fmt.Errorf("multiple audiences support is not implemented") + } + audience = audiences[0] + } + return google.JWTAccessTokenSourceFromJSON(data, audience) +} diff --git a/vendor/google.golang.org/api/internal/pool.go b/vendor/google.golang.org/api/internal/pool.go new file mode 100644 index 00000000..a4426dcb --- /dev/null +++ b/vendor/google.golang.org/api/internal/pool.go @@ -0,0 +1,61 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package internal + +import ( + "errors" + + "google.golang.org/grpc/naming" +) + +// PoolResolver provides a fixed list of addresses to load balance between +// and does not provide further updates. +type PoolResolver struct { + poolSize int + dialOpt *DialSettings + ch chan []*naming.Update +} + +// NewPoolResolver returns a PoolResolver +// This is an EXPERIMENTAL API and may be changed or removed in the future. +func NewPoolResolver(size int, o *DialSettings) *PoolResolver { + return &PoolResolver{poolSize: size, dialOpt: o} +} + +// Resolve returns a Watcher for the endpoint defined by the DialSettings +// provided to NewPoolResolver. +func (r *PoolResolver) Resolve(target string) (naming.Watcher, error) { + if r.dialOpt.Endpoint == "" { + return nil, errors.New("no endpoint configured") + } + addrs := make([]*naming.Update, 0, r.poolSize) + for i := 0; i < r.poolSize; i++ { + addrs = append(addrs, &naming.Update{Op: naming.Add, Addr: r.dialOpt.Endpoint, Metadata: i}) + } + r.ch = make(chan []*naming.Update, 1) + r.ch <- addrs + return r, nil +} + +// Next returns a static list of updates on the first call, +// and blocks indefinitely until Close is called on subsequent calls. +func (r *PoolResolver) Next() ([]*naming.Update, error) { + return <-r.ch, nil +} + +// Close releases resources associated with the pool and causes Next to unblock. +func (r *PoolResolver) Close() { + close(r.ch) +} diff --git a/vendor/google.golang.org/api/internal/service-account.json b/vendor/google.golang.org/api/internal/service-account.json new file mode 100644 index 00000000..6b36a929 --- /dev/null +++ b/vendor/google.golang.org/api/internal/service-account.json @@ -0,0 +1,12 @@ +{ + "type": "service_account", + "project_id": "project_id", + "private_key_id": "private_key_id", + "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCzd9ZdbPLAR4/g\nj+Rodu15kEasMpxf/Mz+gKRb2fmgR2Y18Y/iRBYZ4SkmF2pBSfzvwE/aTCzSPBGl\njHhPzohXnSN029eWoItmxVONlqCbR29pD07aLzv08LGeIGdHIEdhVjhvRwTkYZIF\ndXmlHNDRUU/EbJN9D+3ahw22BNnC4PaDgfIWTs3xIlTCSf2rL39I4DSNLTS/LzxK\n/XrQfBMtfwMWwyQaemXbc7gRgzOy8L56wa1W1zyXx99th97j1bLnoAXBGplhB4Co\n25ohyDAuhxRm+XGMEaO0Mzo7u97kvhj48a569RH1QRhOf7EBf60jO4h5eOmfi5P5\nPV3l7041AgMBAAECggEAEZ0RTNoEeRqM5F067YW+iM/AH+ZXspP9Cn1VpC4gcbqQ\nLXsnw+0qvh97CmIB66Z3TJBzRdl0DK4YjUbcB/kdKHwjnrR01DOtesijCqJd4N+B\n762w73jzSXbV9872U+S3HLZ5k3JE6KUqz55X8fyCAgkY6w4862lEzs2yasrPFHEV\nRoQp3PM0Miif8R3hGDhOWcHxcobullthG6JHAQFfc1ctwEjZI4TK0iWqlzfWGyKN\nT9UgvjUDud5cGvS9el0AiLN6keAf77tcPn1zetUVhxN1KN4bVAm1Q+6O8esl63Rj\n7JXpHzxaRnit9S6/aH/twHsGGtLg5Puw6jey6xs4AQKBgQD2JNy1wzewCRkD+jug\n8CHbJ+LIJVRNIaWa/RK1QD8/UjmFPkIzRQSF3AKC5mRAWSa2FL3yVK3N/DD7hazW\n85XSBB7IDcnoJnA9SkUeWwqQGkDx3EntlU3gX8Kn/+ofF8O9jLXxAa901MAVXVuf\n5YDzrl4PNE3bFnPCdiNmSdRfhQKBgQC6p4DsCpwqbeTu9f5ak9VW/fQP47Fgt+Mf\nwGjBnKP5PbbNJpHCfamF7jqSRH83Xy0KNssH7jD/NZ2oT594sMmiQPUC5ni9VYY6\nsuYB0JbD5Mq+EjKIVhYtxaQJ76LzHreEI+G4z6k3H7/hRpr3/C48n9G/uVkT9DbJ\noplxxEx68QKBgQCdJ23vcwO0Firtmi/GEmtbVHz70rGfSXNFoHz4UlvPXv0wsE5u\nE4vOt2i3EMhDOWh46odYGG6bzH+tp2xyFTW70Dui+QLHgPs6dpfoyLHWzZxXj5F3\n6lK9hgZvYvqk/XRRKmzjwnK2wjsdqOyeC1covlR5mqh20D/6kZkKbur0TQKBgAwy\nCZBimRWEnKKoW/gbFKNccGfhXqONID/g2Hdd/rC4QYth68AjacIgcJ9B7nX1uAGk\n1tsryvPB0w0+NpMyKdp6GAgaeuUUA3MuYSzZLiCagEyu77JMvaI7+Z3UlHcCGMd/\neK4Uk1/QqT7U2Cc/yN2ZK6E1QQa2vCWshA4U31JhAoGAbtbSSSsul1c+PsJ13Cfk\n6qVnqYzPqt23QTyOZmGAvUHH/M4xRiQpOE0cDF4t/r5PwenAQPQzTvMmWRzj6uAY\n3eaU0eAK7ZfoweCoOIAPnpFbbRLrXfoY46H7MYh7euWGXOKEpxz5yzuEkd9ByNUE\n86vSEidqbMIiXVgEgnu/k08=\n-----END PRIVATE KEY-----\n", + "client_email": "xyz@developer.gserviceaccount.com", + "client_id": "123", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://accounts.google.com/o/oauth2/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xyz%40developer.gserviceaccount.com" +} diff --git a/vendor/google.golang.org/api/internal/settings.go b/vendor/google.golang.org/api/internal/settings.go new file mode 100644 index 00000000..062301c6 --- /dev/null +++ b/vendor/google.golang.org/api/internal/settings.go @@ -0,0 +1,96 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package internal supports the options and transport packages. +package internal + +import ( + "errors" + "net/http" + + "golang.org/x/oauth2" + "golang.org/x/oauth2/google" + "google.golang.org/grpc" +) + +// DialSettings holds information needed to establish a connection with a +// Google API service. +type DialSettings struct { + Endpoint string + Scopes []string + TokenSource oauth2.TokenSource + Credentials *google.Credentials + CredentialsFile string // if set, Token Source is ignored. + CredentialsJSON []byte + UserAgent string + APIKey string + Audiences []string + HTTPClient *http.Client + GRPCDialOpts []grpc.DialOption + GRPCConn *grpc.ClientConn + NoAuth bool + + // Google API system parameters. For more information please read: + // https://cloud.google.com/apis/docs/system-parameters + QuotaProject string + RequestReason string +} + +// Validate reports an error if ds is invalid. +func (ds *DialSettings) Validate() error { + hasCreds := ds.APIKey != "" || ds.TokenSource != nil || ds.CredentialsFile != "" || ds.Credentials != nil + if ds.NoAuth && hasCreds { + return errors.New("options.WithoutAuthentication is incompatible with any option that provides credentials") + } + // Credentials should not appear with other options. + // We currently allow TokenSource and CredentialsFile to coexist. + // TODO(jba): make TokenSource & CredentialsFile an error (breaking change). + nCreds := 0 + if ds.Credentials != nil { + nCreds++ + } + if ds.CredentialsJSON != nil { + nCreds++ + } + if ds.CredentialsFile != "" { + nCreds++ + } + if ds.APIKey != "" { + nCreds++ + } + if ds.TokenSource != nil { + nCreds++ + } + if len(ds.Scopes) > 0 && len(ds.Audiences) > 0 { + return errors.New("WithScopes is incompatible with WithAudience") + } + // Accept only one form of credentials, except we allow TokenSource and CredentialsFile for backwards compatibility. + if nCreds > 1 && !(nCreds == 2 && ds.TokenSource != nil && ds.CredentialsFile != "") { + return errors.New("multiple credential options provided") + } + if ds.HTTPClient != nil && ds.GRPCConn != nil { + return errors.New("WithHTTPClient is incompatible with WithGRPCConn") + } + if ds.HTTPClient != nil && ds.GRPCDialOpts != nil { + return errors.New("WithHTTPClient is incompatible with gRPC dial options") + } + if ds.HTTPClient != nil && ds.QuotaProject != "" { + return errors.New("WithHTTPClient is incompatible with QuotaProject") + } + if ds.HTTPClient != nil && ds.RequestReason != "" { + return errors.New("WithHTTPClient is incompatible with RequestReason") + } + + return nil +} diff --git a/vendor/google.golang.org/api/option/credentials_go19.go b/vendor/google.golang.org/api/option/credentials_go19.go new file mode 100644 index 00000000..0636a829 --- /dev/null +++ b/vendor/google.golang.org/api/option/credentials_go19.go @@ -0,0 +1,33 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build go1.9 + +package option + +import ( + "golang.org/x/oauth2/google" + "google.golang.org/api/internal" +) + +type withCreds google.Credentials + +func (w *withCreds) Apply(o *internal.DialSettings) { + o.Credentials = (*google.Credentials)(w) +} + +// WithCredentials returns a ClientOption that authenticates API calls. +func WithCredentials(creds *google.Credentials) ClientOption { + return (*withCreds)(creds) +} diff --git a/vendor/google.golang.org/api/option/credentials_notgo19.go b/vendor/google.golang.org/api/option/credentials_notgo19.go new file mode 100644 index 00000000..74d3a4b5 --- /dev/null +++ b/vendor/google.golang.org/api/option/credentials_notgo19.go @@ -0,0 +1,32 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build !go1.9 + +package option + +import ( + "golang.org/x/oauth2/google" + "google.golang.org/api/internal" +) + +type withCreds google.DefaultCredentials + +func (w *withCreds) Apply(o *internal.DialSettings) { + o.Credentials = (*google.DefaultCredentials)(w) +} + +func WithCredentials(creds *google.DefaultCredentials) ClientOption { + return (*withCreds)(creds) +} diff --git a/vendor/google.golang.org/api/option/option.go b/vendor/google.golang.org/api/option/option.go new file mode 100644 index 00000000..0a1c2dba --- /dev/null +++ b/vendor/google.golang.org/api/option/option.go @@ -0,0 +1,235 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package option contains options for Google API clients. +package option + +import ( + "net/http" + + "golang.org/x/oauth2" + "google.golang.org/api/internal" + "google.golang.org/grpc" +) + +// A ClientOption is an option for a Google API client. +type ClientOption interface { + Apply(*internal.DialSettings) +} + +// WithTokenSource returns a ClientOption that specifies an OAuth2 token +// source to be used as the basis for authentication. +func WithTokenSource(s oauth2.TokenSource) ClientOption { + return withTokenSource{s} +} + +type withTokenSource struct{ ts oauth2.TokenSource } + +func (w withTokenSource) Apply(o *internal.DialSettings) { + o.TokenSource = w.ts +} + +type withCredFile string + +func (w withCredFile) Apply(o *internal.DialSettings) { + o.CredentialsFile = string(w) +} + +// WithCredentialsFile returns a ClientOption that authenticates +// API calls with the given service account or refresh token JSON +// credentials file. +func WithCredentialsFile(filename string) ClientOption { + return withCredFile(filename) +} + +// WithServiceAccountFile returns a ClientOption that uses a Google service +// account credentials file to authenticate. +// +// Deprecated: Use WithCredentialsFile instead. +func WithServiceAccountFile(filename string) ClientOption { + return WithCredentialsFile(filename) +} + +// WithCredentialsJSON returns a ClientOption that authenticates +// API calls with the given service account or refresh token JSON +// credentials. +func WithCredentialsJSON(p []byte) ClientOption { + return withCredentialsJSON(p) +} + +type withCredentialsJSON []byte + +func (w withCredentialsJSON) Apply(o *internal.DialSettings) { + o.CredentialsJSON = make([]byte, len(w)) + copy(o.CredentialsJSON, w) +} + +// WithEndpoint returns a ClientOption that overrides the default endpoint +// to be used for a service. +func WithEndpoint(url string) ClientOption { + return withEndpoint(url) +} + +type withEndpoint string + +func (w withEndpoint) Apply(o *internal.DialSettings) { + o.Endpoint = string(w) +} + +// WithScopes returns a ClientOption that overrides the default OAuth2 scopes +// to be used for a service. +func WithScopes(scope ...string) ClientOption { + return withScopes(scope) +} + +type withScopes []string + +func (w withScopes) Apply(o *internal.DialSettings) { + o.Scopes = make([]string, len(w)) + copy(o.Scopes, w) +} + +// WithUserAgent returns a ClientOption that sets the User-Agent. +func WithUserAgent(ua string) ClientOption { + return withUA(ua) +} + +type withUA string + +func (w withUA) Apply(o *internal.DialSettings) { o.UserAgent = string(w) } + +// WithHTTPClient returns a ClientOption that specifies the HTTP client to use +// as the basis of communications. This option may only be used with services +// that support HTTP as their communication transport. When used, the +// WithHTTPClient option takes precedent over all other supplied options. +func WithHTTPClient(client *http.Client) ClientOption { + return withHTTPClient{client} +} + +type withHTTPClient struct{ client *http.Client } + +func (w withHTTPClient) Apply(o *internal.DialSettings) { + o.HTTPClient = w.client +} + +// WithGRPCConn returns a ClientOption that specifies the gRPC client +// connection to use as the basis of communications. This option many only be +// used with services that support gRPC as their communication transport. When +// used, the WithGRPCConn option takes precedent over all other supplied +// options. +func WithGRPCConn(conn *grpc.ClientConn) ClientOption { + return withGRPCConn{conn} +} + +type withGRPCConn struct{ conn *grpc.ClientConn } + +func (w withGRPCConn) Apply(o *internal.DialSettings) { + o.GRPCConn = w.conn +} + +// WithGRPCDialOption returns a ClientOption that appends a new grpc.DialOption +// to an underlying gRPC dial. It does not work with WithGRPCConn. +func WithGRPCDialOption(opt grpc.DialOption) ClientOption { + return withGRPCDialOption{opt} +} + +type withGRPCDialOption struct{ opt grpc.DialOption } + +func (w withGRPCDialOption) Apply(o *internal.DialSettings) { + o.GRPCDialOpts = append(o.GRPCDialOpts, w.opt) +} + +// WithGRPCConnectionPool returns a ClientOption that creates a pool of gRPC +// connections that requests will be balanced between. +// This is an EXPERIMENTAL API and may be changed or removed in the future. +func WithGRPCConnectionPool(size int) ClientOption { + return withGRPCConnectionPool(size) +} + +type withGRPCConnectionPool int + +func (w withGRPCConnectionPool) Apply(o *internal.DialSettings) { + balancer := grpc.RoundRobin(internal.NewPoolResolver(int(w), o)) + o.GRPCDialOpts = append(o.GRPCDialOpts, grpc.WithBalancer(balancer)) +} + +// WithAPIKey returns a ClientOption that specifies an API key to be used +// as the basis for authentication. +// +// API Keys can only be used for JSON-over-HTTP APIs, including those under +// the import path google.golang.org/api/.... +func WithAPIKey(apiKey string) ClientOption { + return withAPIKey(apiKey) +} + +type withAPIKey string + +func (w withAPIKey) Apply(o *internal.DialSettings) { o.APIKey = string(w) } + +// WithAudiences returns a ClientOption that specifies an audience to be used +// as the audience field ("aud") for the JWT token authentication. +func WithAudiences(audience ...string) ClientOption { + return withAudiences(audience) +} + +type withAudiences []string + +func (w withAudiences) Apply(o *internal.DialSettings) { + o.Audiences = make([]string, len(w)) + copy(o.Audiences, w) +} + +// WithoutAuthentication returns a ClientOption that specifies that no +// authentication should be used. It is suitable only for testing and for +// accessing public resources, like public Google Cloud Storage buckets. +// It is an error to provide both WithoutAuthentication and any of WithAPIKey, +// WithTokenSource, WithCredentialsFile or WithServiceAccountFile. +func WithoutAuthentication() ClientOption { + return withoutAuthentication{} +} + +type withoutAuthentication struct{} + +func (w withoutAuthentication) Apply(o *internal.DialSettings) { o.NoAuth = true } + +// WithQuotaProject returns a ClientOption that specifies the project used +// for quota and billing purposes. +// +// For more information please read: +// https://cloud.google.com/apis/docs/system-parameters +func WithQuotaProject(quotaProject string) ClientOption { + return withQuotaProject(quotaProject) +} + +type withQuotaProject string + +func (w withQuotaProject) Apply(o *internal.DialSettings) { + o.QuotaProject = string(w) +} + +// WithRequestReason returns a ClientOption that specifies a reason for +// making the request, which is intended to be recorded in audit logging. +// An example reason would be a support-case ticket number. +// +// For more information please read: +// https://cloud.google.com/apis/docs/system-parameters +func WithRequestReason(requestReason string) ClientOption { + return withRequestReason(requestReason) +} + +type withRequestReason string + +func (w withRequestReason) Apply(o *internal.DialSettings) { + o.RequestReason = string(w) +} diff --git a/vendor/google.golang.org/api/transport/http/dial.go b/vendor/google.golang.org/api/transport/http/dial.go new file mode 100644 index 00000000..c0d8bf20 --- /dev/null +++ b/vendor/google.golang.org/api/transport/http/dial.go @@ -0,0 +1,161 @@ +// Copyright 2015 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package http supports network connections to HTTP servers. +// This package is not intended for use by end developers. Use the +// google.golang.org/api/option package to configure API clients. +package http + +import ( + "context" + "errors" + "net/http" + + "go.opencensus.io/plugin/ochttp" + "golang.org/x/oauth2" + "google.golang.org/api/googleapi/transport" + "google.golang.org/api/internal" + "google.golang.org/api/option" + "google.golang.org/api/transport/http/internal/propagation" +) + +// NewClient returns an HTTP client for use communicating with a Google cloud +// service, configured with the given ClientOptions. It also returns the endpoint +// for the service as specified in the options. +func NewClient(ctx context.Context, opts ...option.ClientOption) (*http.Client, string, error) { + settings, err := newSettings(opts) + if err != nil { + return nil, "", err + } + // TODO(cbro): consider injecting the User-Agent even if an explicit HTTP client is provided? + if settings.HTTPClient != nil { + return settings.HTTPClient, settings.Endpoint, nil + } + trans, err := newTransport(ctx, defaultBaseTransport(ctx), settings) + if err != nil { + return nil, "", err + } + return &http.Client{Transport: trans}, settings.Endpoint, nil +} + +// NewTransport creates an http.RoundTripper for use communicating with a Google +// cloud service, configured with the given ClientOptions. Its RoundTrip method delegates to base. +func NewTransport(ctx context.Context, base http.RoundTripper, opts ...option.ClientOption) (http.RoundTripper, error) { + settings, err := newSettings(opts) + if err != nil { + return nil, err + } + if settings.HTTPClient != nil { + return nil, errors.New("transport/http: WithHTTPClient passed to NewTransport") + } + return newTransport(ctx, base, settings) +} + +func newTransport(ctx context.Context, base http.RoundTripper, settings *internal.DialSettings) (http.RoundTripper, error) { + trans := base + trans = parameterTransport{ + base: trans, + userAgent: settings.UserAgent, + quotaProject: settings.QuotaProject, + requestReason: settings.RequestReason, + } + trans = addOCTransport(trans) + switch { + case settings.NoAuth: + // Do nothing. + case settings.APIKey != "": + trans = &transport.APIKey{ + Transport: trans, + Key: settings.APIKey, + } + default: + creds, err := internal.Creds(ctx, settings) + if err != nil { + return nil, err + } + trans = &oauth2.Transport{ + Base: trans, + Source: creds.TokenSource, + } + } + return trans, nil +} + +func newSettings(opts []option.ClientOption) (*internal.DialSettings, error) { + var o internal.DialSettings + for _, opt := range opts { + opt.Apply(&o) + } + if err := o.Validate(); err != nil { + return nil, err + } + if o.GRPCConn != nil { + return nil, errors.New("unsupported gRPC connection specified") + } + return &o, nil +} + +type parameterTransport struct { + userAgent string + quotaProject string + requestReason string + + base http.RoundTripper +} + +func (t parameterTransport) RoundTrip(req *http.Request) (*http.Response, error) { + rt := t.base + if rt == nil { + return nil, errors.New("transport: no Transport specified") + } + if t.userAgent == "" { + return rt.RoundTrip(req) + } + newReq := *req + newReq.Header = make(http.Header) + for k, vv := range req.Header { + newReq.Header[k] = vv + } + // TODO(cbro): append to existing User-Agent header? + newReq.Header.Set("User-Agent", t.userAgent) + + // Attach system parameters into the header + if t.quotaProject != "" { + newReq.Header.Set("X-Goog-User-Project", t.quotaProject) + } + if t.requestReason != "" { + newReq.Header.Set("X-Goog-Request-Reason", t.requestReason) + } + + return rt.RoundTrip(&newReq) +} + +// Set at init time by dial_appengine.go. If nil, we're not on App Engine. +var appengineUrlfetchHook func(context.Context) http.RoundTripper + +// defaultBaseTransport returns the base HTTP transport. +// On App Engine, this is urlfetch.Transport, otherwise it's http.DefaultTransport. +func defaultBaseTransport(ctx context.Context) http.RoundTripper { + if appengineUrlfetchHook != nil { + return appengineUrlfetchHook(ctx) + } + return http.DefaultTransport +} + +func addOCTransport(trans http.RoundTripper) http.RoundTripper { + return &ochttp.Transport{ + Base: trans, + Propagation: &propagation.HTTPFormat{}, + } +} diff --git a/vendor/google.golang.org/api/transport/http/dial_appengine.go b/vendor/google.golang.org/api/transport/http/dial_appengine.go new file mode 100644 index 00000000..04c81413 --- /dev/null +++ b/vendor/google.golang.org/api/transport/http/dial_appengine.go @@ -0,0 +1,30 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build appengine + +package http + +import ( + "context" + "net/http" + + "google.golang.org/appengine/urlfetch" +) + +func init() { + appengineUrlfetchHook = func(ctx context.Context) http.RoundTripper { + return &urlfetch.Transport{Context: ctx} + } +} diff --git a/vendor/google.golang.org/api/transport/http/internal/propagation/http.go b/vendor/google.golang.org/api/transport/http/internal/propagation/http.go new file mode 100644 index 00000000..24b4f0d2 --- /dev/null +++ b/vendor/google.golang.org/api/transport/http/internal/propagation/http.go @@ -0,0 +1,96 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build go1.8 + +// Package propagation implements X-Cloud-Trace-Context header propagation used +// by Google Cloud products. +package propagation + +import ( + "encoding/binary" + "encoding/hex" + "fmt" + "net/http" + "strconv" + "strings" + + "go.opencensus.io/trace" + "go.opencensus.io/trace/propagation" +) + +const ( + httpHeaderMaxSize = 200 + httpHeader = `X-Cloud-Trace-Context` +) + +var _ propagation.HTTPFormat = (*HTTPFormat)(nil) + +// HTTPFormat implements propagation.HTTPFormat to propagate +// traces in HTTP headers for Google Cloud Platform and Stackdriver Trace. +type HTTPFormat struct{} + +// SpanContextFromRequest extracts a Stackdriver Trace span context from incoming requests. +func (f *HTTPFormat) SpanContextFromRequest(req *http.Request) (sc trace.SpanContext, ok bool) { + h := req.Header.Get(httpHeader) + // See https://cloud.google.com/trace/docs/faq for the header HTTPFormat. + // Return if the header is empty or missing, or if the header is unreasonably + // large, to avoid making unnecessary copies of a large string. + if h == "" || len(h) > httpHeaderMaxSize { + return trace.SpanContext{}, false + } + + // Parse the trace id field. + slash := strings.Index(h, `/`) + if slash == -1 { + return trace.SpanContext{}, false + } + tid, h := h[:slash], h[slash+1:] + + buf, err := hex.DecodeString(tid) + if err != nil { + return trace.SpanContext{}, false + } + copy(sc.TraceID[:], buf) + + // Parse the span id field. + spanstr := h + semicolon := strings.Index(h, `;`) + if semicolon != -1 { + spanstr, h = h[:semicolon], h[semicolon+1:] + } + sid, err := strconv.ParseUint(spanstr, 10, 64) + if err != nil { + return trace.SpanContext{}, false + } + binary.BigEndian.PutUint64(sc.SpanID[:], sid) + + // Parse the options field, options field is optional. + if !strings.HasPrefix(h, "o=") { + return sc, true + } + o, err := strconv.ParseUint(h[2:], 10, 64) + if err != nil { + return trace.SpanContext{}, false + } + sc.TraceOptions = trace.TraceOptions(o) + return sc, true +} + +// SpanContextToRequest modifies the given request to include a Stackdriver Trace header. +func (f *HTTPFormat) SpanContextToRequest(sc trace.SpanContext, req *http.Request) { + sid := binary.BigEndian.Uint64(sc.SpanID[:]) + header := fmt.Sprintf("%s/%d;o=%d", hex.EncodeToString(sc.TraceID[:]), sid, int64(sc.TraceOptions)) + req.Header.Set(httpHeader, header) +} diff --git a/vendor/google.golang.org/appengine/.travis.yml b/vendor/google.golang.org/appengine/.travis.yml new file mode 100644 index 00000000..70ffe89d --- /dev/null +++ b/vendor/google.golang.org/appengine/.travis.yml @@ -0,0 +1,20 @@ +language: go + +go_import_path: google.golang.org/appengine + +install: + - ./travis_install.sh + +script: + - ./travis_test.sh + +matrix: + include: + - go: 1.8.x + env: GOAPP=true + - go: 1.9.x + env: GOAPP=true + - go: 1.10.x + env: GOAPP=false + - go: 1.11.x + env: GO111MODULE=on diff --git a/vendor/google.golang.org/appengine/CONTRIBUTING.md b/vendor/google.golang.org/appengine/CONTRIBUTING.md new file mode 100644 index 00000000..ffc29852 --- /dev/null +++ b/vendor/google.golang.org/appengine/CONTRIBUTING.md @@ -0,0 +1,90 @@ +# Contributing + +1. Sign one of the contributor license agreements below. +1. Get the package: + + `go get -d google.golang.org/appengine` +1. Change into the checked out source: + + `cd $GOPATH/src/google.golang.org/appengine` +1. Fork the repo. +1. Set your fork as a remote: + + `git remote add fork git@github.com:GITHUB_USERNAME/appengine.git` +1. Make changes, commit to your fork. +1. Send a pull request with your changes. + The first line of your commit message is conventionally a one-line summary of the change, prefixed by the primary affected package, and is used as the title of your pull request. + +# Testing + +## Running system tests + +Download and install the [Go App Engine SDK](https://cloud.google.com/appengine/docs/go/download). Make sure the `go_appengine` dir is in your `PATH`. + +Set the `APPENGINE_DEV_APPSERVER` environment variable to `/path/to/go_appengine/dev_appserver.py`. + +Run tests with `goapp test`: + +``` +goapp test -v google.golang.org/appengine/... +``` + +## Contributor License Agreements + +Before we can accept your pull requests you'll need to sign a Contributor +License Agreement (CLA): + +- **If you are an individual writing original source code** and **you own the +intellectual property**, then you'll need to sign an [individual CLA][indvcla]. +- **If you work for a company that wants to allow you to contribute your work**, +then you'll need to sign a [corporate CLA][corpcla]. + +You can sign these electronically (just scroll to the bottom). After that, +we'll be able to accept your pull requests. + +## Contributor Code of Conduct + +As contributors and maintainers of this project, +and in the interest of fostering an open and welcoming community, +we pledge to respect all people who contribute through reporting issues, +posting feature requests, updating documentation, +submitting pull requests or patches, and other activities. + +We are committed to making participation in this project +a harassment-free experience for everyone, +regardless of level of experience, gender, gender identity and expression, +sexual orientation, disability, personal appearance, +body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, +such as physical or electronic +addresses, without explicit permission +* Other unethical or unprofessional conduct. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct. +By adopting this Code of Conduct, +project maintainers commit themselves to fairly and consistently +applying these principles to every aspect of managing this project. +Project maintainers who do not follow or enforce the Code of Conduct +may be permanently removed from the project team. + +This code of conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior +may be reported by opening an issue +or contacting one or more of the project maintainers. + +This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, +available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) + +[indvcla]: https://developers.google.com/open-source/cla/individual +[corpcla]: https://developers.google.com/open-source/cla/corporate diff --git a/vendor/google.golang.org/appengine/README.md b/vendor/google.golang.org/appengine/README.md new file mode 100644 index 00000000..9fdbacd3 --- /dev/null +++ b/vendor/google.golang.org/appengine/README.md @@ -0,0 +1,100 @@ +# Go App Engine packages + +[![Build Status](https://travis-ci.org/golang/appengine.svg)](https://travis-ci.org/golang/appengine) + +This repository supports the Go runtime on *App Engine standard*. +It provides APIs for interacting with App Engine services. +Its canonical import path is `google.golang.org/appengine`. + +See https://cloud.google.com/appengine/docs/go/ +for more information. + +File issue reports and feature requests on the [GitHub's issue +tracker](https://github.com/golang/appengine/issues). + +## Upgrading an App Engine app to the flexible environment + +This package does not work on *App Engine flexible*. + +There are many differences between the App Engine standard environment and +the flexible environment. + +See the [documentation on upgrading to the flexible environment](https://cloud.google.com/appengine/docs/flexible/go/upgrading). + +## Directory structure + +The top level directory of this repository is the `appengine` package. It +contains the +basic APIs (e.g. `appengine.NewContext`) that apply across APIs. Specific API +packages are in subdirectories (e.g. `datastore`). + +There is an `internal` subdirectory that contains service protocol buffers, +plus packages required for connectivity to make API calls. App Engine apps +should not directly import any package under `internal`. + +## Updating from legacy (`import "appengine"`) packages + +If you're currently using the bare `appengine` packages +(that is, not these ones, imported via `google.golang.org/appengine`), +then you can use the `aefix` tool to help automate an upgrade to these packages. + +Run `go get google.golang.org/appengine/cmd/aefix` to install it. + +### 1. Update import paths + +The import paths for App Engine packages are now fully qualified, based at `google.golang.org/appengine`. +You will need to update your code to use import paths starting with that; for instance, +code importing `appengine/datastore` will now need to import `google.golang.org/appengine/datastore`. + +### 2. Update code using deprecated, removed or modified APIs + +Most App Engine services are available with exactly the same API. +A few APIs were cleaned up, and there are some differences: + +* `appengine.Context` has been replaced with the `Context` type from `golang.org/x/net/context`. +* Logging methods that were on `appengine.Context` are now functions in `google.golang.org/appengine/log`. +* `appengine.Timeout` has been removed. Use `context.WithTimeout` instead. +* `appengine.Datacenter` now takes a `context.Context` argument. +* `datastore.PropertyLoadSaver` has been simplified to use slices in place of channels. +* `delay.Call` now returns an error. +* `search.FieldLoadSaver` now handles document metadata. +* `urlfetch.Transport` no longer has a Deadline field; set a deadline on the + `context.Context` instead. +* `aetest` no longer declares its own Context type, and uses the standard one instead. +* `taskqueue.QueueStats` no longer takes a maxTasks argument. That argument has been + deprecated and unused for a long time. +* `appengine.BackendHostname` and `appengine.BackendInstance` were for the deprecated backends feature. + Use `appengine.ModuleHostname`and `appengine.ModuleName` instead. +* Most of `appengine/file` and parts of `appengine/blobstore` are deprecated. + Use [Google Cloud Storage](https://godoc.org/cloud.google.com/go/storage) if the + feature you require is not present in the new + [blobstore package](https://google.golang.org/appengine/blobstore). +* `appengine/socket` is not required on App Engine flexible environment / Managed VMs. + Use the standard `net` package instead. + +## Key Encode/Decode compatibiltiy to help with datastore library migrations + +Key compatibility updates have been added to help customers transition from google.golang.org/appengine/datastore to cloud.google.com/go/datastore. +The `EnableKeyConversion` enables automatic conversion from a key encoded with cloud.google.com/go/datastore to google.golang.org/appengine/datastore key type. + +### Enabling key conversion + +Enable key conversion by calling `EnableKeyConversion(ctx)` in the `/_ah/start` handler for basic and manual scaling or any handler in automatic scaling. + +#### 1. Basic or manual scaling + +This start handler will enable key conversion for all handlers in the service. + +``` +http.HandleFunc("/_ah/start", func(w http.ResponseWriter, r *http.Request) { + datastore.EnableKeyConversion(appengine.NewContext(r)) +}) +``` + +#### 2. Automatic scaling + +`/_ah/start` is not supported for automatic scaling and `/_ah/warmup` is not guaranteed to run, so you must call `datastore.EnableKeyConversion(appengine.NewContext(r))` +before you use code that needs key conversion. + +You may want to add this to each of your handlers, or introduce middleware where it's called. +`EnableKeyConversion` is safe for concurrent use. Any call to it after the first is ignored. \ No newline at end of file diff --git a/vendor/google.golang.org/appengine/appengine.go b/vendor/google.golang.org/appengine/appengine.go new file mode 100644 index 00000000..8c969767 --- /dev/null +++ b/vendor/google.golang.org/appengine/appengine.go @@ -0,0 +1,135 @@ +// Copyright 2011 Google Inc. All rights reserved. +// Use of this source code is governed by the Apache 2.0 +// license that can be found in the LICENSE file. + +// Package appengine provides basic functionality for Google App Engine. +// +// For more information on how to write Go apps for Google App Engine, see: +// https://cloud.google.com/appengine/docs/go/ +package appengine // import "google.golang.org/appengine" + +import ( + "net/http" + + "github.com/golang/protobuf/proto" + "golang.org/x/net/context" + + "google.golang.org/appengine/internal" +) + +// The gophers party all night; the rabbits provide the beats. + +// Main is the principal entry point for an app running in App Engine. +// +// On App Engine Flexible it installs a trivial health checker if one isn't +// already registered, and starts listening on port 8080 (overridden by the +// $PORT environment variable). +// +// See https://cloud.google.com/appengine/docs/flexible/custom-runtimes#health_check_requests +// for details on how to do your own health checking. +// +// On App Engine Standard it ensures the server has started and is prepared to +// receive requests. +// +// Main never returns. +// +// Main is designed so that the app's main package looks like this: +// +// package main +// +// import ( +// "google.golang.org/appengine" +// +// _ "myapp/package0" +// _ "myapp/package1" +// ) +// +// func main() { +// appengine.Main() +// } +// +// The "myapp/packageX" packages are expected to register HTTP handlers +// in their init functions. +func Main() { + internal.Main() +} + +// IsDevAppServer reports whether the App Engine app is running in the +// development App Server. +func IsDevAppServer() bool { + return internal.IsDevAppServer() +} + +// IsStandard reports whether the App Engine app is running in the standard +// environment. This includes both the first generation runtimes (<= Go 1.9) +// and the second generation runtimes (>= Go 1.11). +func IsStandard() bool { + return internal.IsStandard() +} + +// IsFlex reports whether the App Engine app is running in the flexible environment. +func IsFlex() bool { + return internal.IsFlex() +} + +// IsAppEngine reports whether the App Engine app is running on App Engine, in either +// the standard or flexible environment. +func IsAppEngine() bool { + return internal.IsAppEngine() +} + +// IsSecondGen reports whether the App Engine app is running on the second generation +// runtimes (>= Go 1.11). +func IsSecondGen() bool { + return internal.IsSecondGen() +} + +// NewContext returns a context for an in-flight HTTP request. +// This function is cheap. +func NewContext(req *http.Request) context.Context { + return internal.ReqContext(req) +} + +// WithContext returns a copy of the parent context +// and associates it with an in-flight HTTP request. +// This function is cheap. +func WithContext(parent context.Context, req *http.Request) context.Context { + return internal.WithContext(parent, req) +} + +// BlobKey is a key for a blobstore blob. +// +// Conceptually, this type belongs in the blobstore package, but it lives in +// the appengine package to avoid a circular dependency: blobstore depends on +// datastore, and datastore needs to refer to the BlobKey type. +type BlobKey string + +// GeoPoint represents a location as latitude/longitude in degrees. +type GeoPoint struct { + Lat, Lng float64 +} + +// Valid returns whether a GeoPoint is within [-90, 90] latitude and [-180, 180] longitude. +func (g GeoPoint) Valid() bool { + return -90 <= g.Lat && g.Lat <= 90 && -180 <= g.Lng && g.Lng <= 180 +} + +// APICallFunc defines a function type for handling an API call. +// See WithCallOverride. +type APICallFunc func(ctx context.Context, service, method string, in, out proto.Message) error + +// WithAPICallFunc returns a copy of the parent context +// that will cause API calls to invoke f instead of their normal operation. +// +// This is intended for advanced users only. +func WithAPICallFunc(ctx context.Context, f APICallFunc) context.Context { + return internal.WithCallOverride(ctx, internal.CallOverrideFunc(f)) +} + +// APICall performs an API call. +// +// This is not intended for general use; it is exported for use in conjunction +// with WithAPICallFunc. +func APICall(ctx context.Context, service, method string, in, out proto.Message) error { + return internal.Call(ctx, service, method, in, out) +} diff --git a/vendor/google.golang.org/appengine/appengine_vm.go b/vendor/google.golang.org/appengine/appengine_vm.go new file mode 100644 index 00000000..f4b645aa --- /dev/null +++ b/vendor/google.golang.org/appengine/appengine_vm.go @@ -0,0 +1,20 @@ +// Copyright 2015 Google Inc. All rights reserved. +// Use of this source code is governed by the Apache 2.0 +// license that can be found in the LICENSE file. + +// +build !appengine + +package appengine + +import ( + "golang.org/x/net/context" + + "google.golang.org/appengine/internal" +) + +// BackgroundContext returns a context not associated with a request. +// This should only be used when not servicing a request. +// This only works in App Engine "flexible environment". +func BackgroundContext() context.Context { + return internal.BackgroundContext() +} diff --git a/vendor/google.golang.org/appengine/errors.go b/vendor/google.golang.org/appengine/errors.go new file mode 100644 index 00000000..16d0772e --- /dev/null +++ b/vendor/google.golang.org/appengine/errors.go @@ -0,0 +1,46 @@ +// Copyright 2011 Google Inc. All rights reserved. +// Use of this source code is governed by the Apache 2.0 +// license that can be found in the LICENSE file. + +// This file provides error functions for common API failure modes. + +package appengine + +import ( + "fmt" + + "google.golang.org/appengine/internal" +) + +// IsOverQuota reports whether err represents an API call failure +// due to insufficient available quota. +func IsOverQuota(err error) bool { + callErr, ok := err.(*internal.CallError) + return ok && callErr.Code == 4 +} + +// MultiError is returned by batch operations when there are errors with +// particular elements. Errors will be in a one-to-one correspondence with +// the input elements; successful elements will have a nil entry. +type MultiError []error + +func (m MultiError) Error() string { + s, n := "", 0 + for _, e := range m { + if e != nil { + if n == 0 { + s = e.Error() + } + n++ + } + } + switch n { + case 0: + return "(0 errors)" + case 1: + return s + case 2: + return s + " (and 1 other error)" + } + return fmt.Sprintf("%s (and %d other errors)", s, n-1) +} diff --git a/vendor/google.golang.org/appengine/go.mod b/vendor/google.golang.org/appengine/go.mod new file mode 100644 index 00000000..45159279 --- /dev/null +++ b/vendor/google.golang.org/appengine/go.mod @@ -0,0 +1,10 @@ +module google.golang.org/appengine + +require ( + github.com/golang/protobuf v1.3.1 + golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5 // indirect + golang.org/x/net v0.0.0-20190603091049-60506f45cf65 + golang.org/x/sys v0.0.0-20190606165138-5da285871e9c // indirect + golang.org/x/text v0.3.2 + golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b // indirect +) diff --git a/vendor/google.golang.org/appengine/go.sum b/vendor/google.golang.org/appengine/go.sum new file mode 100644 index 00000000..cb323255 --- /dev/null +++ b/vendor/google.golang.org/appengine/go.sum @@ -0,0 +1,22 @@ +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225 h1:kNX+jCowfMYzvlSvJu5pQWEmyWFrBXJ3PBy10xKMXK8= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65 h1:+rhAzEzT3f4JtomfC371qB+0Ola2caSKcY69NUBZrRQ= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= diff --git a/vendor/google.golang.org/appengine/identity.go b/vendor/google.golang.org/appengine/identity.go new file mode 100644 index 00000000..b8dcf8f3 --- /dev/null +++ b/vendor/google.golang.org/appengine/identity.go @@ -0,0 +1,142 @@ +// Copyright 2011 Google Inc. All rights reserved. +// Use of this source code is governed by the Apache 2.0 +// license that can be found in the LICENSE file. + +package appengine + +import ( + "time" + + "golang.org/x/net/context" + + "google.golang.org/appengine/internal" + pb "google.golang.org/appengine/internal/app_identity" + modpb "google.golang.org/appengine/internal/modules" +) + +// AppID returns the application ID for the current application. +// The string will be a plain application ID (e.g. "appid"), with a +// domain prefix for custom domain deployments (e.g. "example.com:appid"). +func AppID(c context.Context) string { return internal.AppID(c) } + +// DefaultVersionHostname returns the standard hostname of the default version +// of the current application (e.g. "my-app.appspot.com"). This is suitable for +// use in constructing URLs. +func DefaultVersionHostname(c context.Context) string { + return internal.DefaultVersionHostname(c) +} + +// ModuleName returns the module name of the current instance. +func ModuleName(c context.Context) string { + return internal.ModuleName(c) +} + +// ModuleHostname returns a hostname of a module instance. +// If module is the empty string, it refers to the module of the current instance. +// If version is empty, it refers to the version of the current instance if valid, +// or the default version of the module of the current instance. +// If instance is empty, ModuleHostname returns the load-balancing hostname. +func ModuleHostname(c context.Context, module, version, instance string) (string, error) { + req := &modpb.GetHostnameRequest{} + if module != "" { + req.Module = &module + } + if version != "" { + req.Version = &version + } + if instance != "" { + req.Instance = &instance + } + res := &modpb.GetHostnameResponse{} + if err := internal.Call(c, "modules", "GetHostname", req, res); err != nil { + return "", err + } + return *res.Hostname, nil +} + +// VersionID returns the version ID for the current application. +// It will be of the form "X.Y", where X is specified in app.yaml, +// and Y is a number generated when each version of the app is uploaded. +// It does not include a module name. +func VersionID(c context.Context) string { return internal.VersionID(c) } + +// InstanceID returns a mostly-unique identifier for this instance. +func InstanceID() string { return internal.InstanceID() } + +// Datacenter returns an identifier for the datacenter that the instance is running in. +func Datacenter(c context.Context) string { return internal.Datacenter(c) } + +// ServerSoftware returns the App Engine release version. +// In production, it looks like "Google App Engine/X.Y.Z". +// In the development appserver, it looks like "Development/X.Y". +func ServerSoftware() string { return internal.ServerSoftware() } + +// RequestID returns a string that uniquely identifies the request. +func RequestID(c context.Context) string { return internal.RequestID(c) } + +// AccessToken generates an OAuth2 access token for the specified scopes on +// behalf of service account of this application. This token will expire after +// the returned time. +func AccessToken(c context.Context, scopes ...string) (token string, expiry time.Time, err error) { + req := &pb.GetAccessTokenRequest{Scope: scopes} + res := &pb.GetAccessTokenResponse{} + + err = internal.Call(c, "app_identity_service", "GetAccessToken", req, res) + if err != nil { + return "", time.Time{}, err + } + return res.GetAccessToken(), time.Unix(res.GetExpirationTime(), 0), nil +} + +// Certificate represents a public certificate for the app. +type Certificate struct { + KeyName string + Data []byte // PEM-encoded X.509 certificate +} + +// PublicCertificates retrieves the public certificates for the app. +// They can be used to verify a signature returned by SignBytes. +func PublicCertificates(c context.Context) ([]Certificate, error) { + req := &pb.GetPublicCertificateForAppRequest{} + res := &pb.GetPublicCertificateForAppResponse{} + if err := internal.Call(c, "app_identity_service", "GetPublicCertificatesForApp", req, res); err != nil { + return nil, err + } + var cs []Certificate + for _, pc := range res.PublicCertificateList { + cs = append(cs, Certificate{ + KeyName: pc.GetKeyName(), + Data: []byte(pc.GetX509CertificatePem()), + }) + } + return cs, nil +} + +// ServiceAccount returns a string representing the service account name, in +// the form of an email address (typically app_id@appspot.gserviceaccount.com). +func ServiceAccount(c context.Context) (string, error) { + req := &pb.GetServiceAccountNameRequest{} + res := &pb.GetServiceAccountNameResponse{} + + err := internal.Call(c, "app_identity_service", "GetServiceAccountName", req, res) + if err != nil { + return "", err + } + return res.GetServiceAccountName(), err +} + +// SignBytes signs bytes using a private key unique to your application. +func SignBytes(c context.Context, bytes []byte) (keyName string, signature []byte, err error) { + req := &pb.SignForAppRequest{BytesToSign: bytes} + res := &pb.SignForAppResponse{} + + if err := internal.Call(c, "app_identity_service", "SignForApp", req, res); err != nil { + return "", nil, err + } + return res.GetKeyName(), res.GetSignatureBytes(), nil +} + +func init() { + internal.RegisterErrorCodeMap("app_identity_service", pb.AppIdentityServiceError_ErrorCode_name) + internal.RegisterErrorCodeMap("modules", modpb.ModulesServiceError_ErrorCode_name) +} diff --git a/vendor/google.golang.org/appengine/internal/app_identity/app_identity_service.pb.go b/vendor/google.golang.org/appengine/internal/app_identity/app_identity_service.pb.go new file mode 100644 index 00000000..9a2ff77a --- /dev/null +++ b/vendor/google.golang.org/appengine/internal/app_identity/app_identity_service.pb.go @@ -0,0 +1,611 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: google.golang.org/appengine/internal/app_identity/app_identity_service.proto + +package app_identity + +import proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package + +type AppIdentityServiceError_ErrorCode int32 + +const ( + AppIdentityServiceError_SUCCESS AppIdentityServiceError_ErrorCode = 0 + AppIdentityServiceError_UNKNOWN_SCOPE AppIdentityServiceError_ErrorCode = 9 + AppIdentityServiceError_BLOB_TOO_LARGE AppIdentityServiceError_ErrorCode = 1000 + AppIdentityServiceError_DEADLINE_EXCEEDED AppIdentityServiceError_ErrorCode = 1001 + AppIdentityServiceError_NOT_A_VALID_APP AppIdentityServiceError_ErrorCode = 1002 + AppIdentityServiceError_UNKNOWN_ERROR AppIdentityServiceError_ErrorCode = 1003 + AppIdentityServiceError_NOT_ALLOWED AppIdentityServiceError_ErrorCode = 1005 + AppIdentityServiceError_NOT_IMPLEMENTED AppIdentityServiceError_ErrorCode = 1006 +) + +var AppIdentityServiceError_ErrorCode_name = map[int32]string{ + 0: "SUCCESS", + 9: "UNKNOWN_SCOPE", + 1000: "BLOB_TOO_LARGE", + 1001: "DEADLINE_EXCEEDED", + 1002: "NOT_A_VALID_APP", + 1003: "UNKNOWN_ERROR", + 1005: "NOT_ALLOWED", + 1006: "NOT_IMPLEMENTED", +} +var AppIdentityServiceError_ErrorCode_value = map[string]int32{ + "SUCCESS": 0, + "UNKNOWN_SCOPE": 9, + "BLOB_TOO_LARGE": 1000, + "DEADLINE_EXCEEDED": 1001, + "NOT_A_VALID_APP": 1002, + "UNKNOWN_ERROR": 1003, + "NOT_ALLOWED": 1005, + "NOT_IMPLEMENTED": 1006, +} + +func (x AppIdentityServiceError_ErrorCode) Enum() *AppIdentityServiceError_ErrorCode { + p := new(AppIdentityServiceError_ErrorCode) + *p = x + return p +} +func (x AppIdentityServiceError_ErrorCode) String() string { + return proto.EnumName(AppIdentityServiceError_ErrorCode_name, int32(x)) +} +func (x *AppIdentityServiceError_ErrorCode) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(AppIdentityServiceError_ErrorCode_value, data, "AppIdentityServiceError_ErrorCode") + if err != nil { + return err + } + *x = AppIdentityServiceError_ErrorCode(value) + return nil +} +func (AppIdentityServiceError_ErrorCode) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_app_identity_service_08a6e3f74b04cfa4, []int{0, 0} +} + +type AppIdentityServiceError struct { + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *AppIdentityServiceError) Reset() { *m = AppIdentityServiceError{} } +func (m *AppIdentityServiceError) String() string { return proto.CompactTextString(m) } +func (*AppIdentityServiceError) ProtoMessage() {} +func (*AppIdentityServiceError) Descriptor() ([]byte, []int) { + return fileDescriptor_app_identity_service_08a6e3f74b04cfa4, []int{0} +} +func (m *AppIdentityServiceError) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_AppIdentityServiceError.Unmarshal(m, b) +} +func (m *AppIdentityServiceError) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_AppIdentityServiceError.Marshal(b, m, deterministic) +} +func (dst *AppIdentityServiceError) XXX_Merge(src proto.Message) { + xxx_messageInfo_AppIdentityServiceError.Merge(dst, src) +} +func (m *AppIdentityServiceError) XXX_Size() int { + return xxx_messageInfo_AppIdentityServiceError.Size(m) +} +func (m *AppIdentityServiceError) XXX_DiscardUnknown() { + xxx_messageInfo_AppIdentityServiceError.DiscardUnknown(m) +} + +var xxx_messageInfo_AppIdentityServiceError proto.InternalMessageInfo + +type SignForAppRequest struct { + BytesToSign []byte `protobuf:"bytes,1,opt,name=bytes_to_sign,json=bytesToSign" json:"bytes_to_sign,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *SignForAppRequest) Reset() { *m = SignForAppRequest{} } +func (m *SignForAppRequest) String() string { return proto.CompactTextString(m) } +func (*SignForAppRequest) ProtoMessage() {} +func (*SignForAppRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_app_identity_service_08a6e3f74b04cfa4, []int{1} +} +func (m *SignForAppRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_SignForAppRequest.Unmarshal(m, b) +} +func (m *SignForAppRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_SignForAppRequest.Marshal(b, m, deterministic) +} +func (dst *SignForAppRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_SignForAppRequest.Merge(dst, src) +} +func (m *SignForAppRequest) XXX_Size() int { + return xxx_messageInfo_SignForAppRequest.Size(m) +} +func (m *SignForAppRequest) XXX_DiscardUnknown() { + xxx_messageInfo_SignForAppRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_SignForAppRequest proto.InternalMessageInfo + +func (m *SignForAppRequest) GetBytesToSign() []byte { + if m != nil { + return m.BytesToSign + } + return nil +} + +type SignForAppResponse struct { + KeyName *string `protobuf:"bytes,1,opt,name=key_name,json=keyName" json:"key_name,omitempty"` + SignatureBytes []byte `protobuf:"bytes,2,opt,name=signature_bytes,json=signatureBytes" json:"signature_bytes,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *SignForAppResponse) Reset() { *m = SignForAppResponse{} } +func (m *SignForAppResponse) String() string { return proto.CompactTextString(m) } +func (*SignForAppResponse) ProtoMessage() {} +func (*SignForAppResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_app_identity_service_08a6e3f74b04cfa4, []int{2} +} +func (m *SignForAppResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_SignForAppResponse.Unmarshal(m, b) +} +func (m *SignForAppResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_SignForAppResponse.Marshal(b, m, deterministic) +} +func (dst *SignForAppResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_SignForAppResponse.Merge(dst, src) +} +func (m *SignForAppResponse) XXX_Size() int { + return xxx_messageInfo_SignForAppResponse.Size(m) +} +func (m *SignForAppResponse) XXX_DiscardUnknown() { + xxx_messageInfo_SignForAppResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_SignForAppResponse proto.InternalMessageInfo + +func (m *SignForAppResponse) GetKeyName() string { + if m != nil && m.KeyName != nil { + return *m.KeyName + } + return "" +} + +func (m *SignForAppResponse) GetSignatureBytes() []byte { + if m != nil { + return m.SignatureBytes + } + return nil +} + +type GetPublicCertificateForAppRequest struct { + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetPublicCertificateForAppRequest) Reset() { *m = GetPublicCertificateForAppRequest{} } +func (m *GetPublicCertificateForAppRequest) String() string { return proto.CompactTextString(m) } +func (*GetPublicCertificateForAppRequest) ProtoMessage() {} +func (*GetPublicCertificateForAppRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_app_identity_service_08a6e3f74b04cfa4, []int{3} +} +func (m *GetPublicCertificateForAppRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetPublicCertificateForAppRequest.Unmarshal(m, b) +} +func (m *GetPublicCertificateForAppRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetPublicCertificateForAppRequest.Marshal(b, m, deterministic) +} +func (dst *GetPublicCertificateForAppRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetPublicCertificateForAppRequest.Merge(dst, src) +} +func (m *GetPublicCertificateForAppRequest) XXX_Size() int { + return xxx_messageInfo_GetPublicCertificateForAppRequest.Size(m) +} +func (m *GetPublicCertificateForAppRequest) XXX_DiscardUnknown() { + xxx_messageInfo_GetPublicCertificateForAppRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_GetPublicCertificateForAppRequest proto.InternalMessageInfo + +type PublicCertificate struct { + KeyName *string `protobuf:"bytes,1,opt,name=key_name,json=keyName" json:"key_name,omitempty"` + X509CertificatePem *string `protobuf:"bytes,2,opt,name=x509_certificate_pem,json=x509CertificatePem" json:"x509_certificate_pem,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *PublicCertificate) Reset() { *m = PublicCertificate{} } +func (m *PublicCertificate) String() string { return proto.CompactTextString(m) } +func (*PublicCertificate) ProtoMessage() {} +func (*PublicCertificate) Descriptor() ([]byte, []int) { + return fileDescriptor_app_identity_service_08a6e3f74b04cfa4, []int{4} +} +func (m *PublicCertificate) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_PublicCertificate.Unmarshal(m, b) +} +func (m *PublicCertificate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_PublicCertificate.Marshal(b, m, deterministic) +} +func (dst *PublicCertificate) XXX_Merge(src proto.Message) { + xxx_messageInfo_PublicCertificate.Merge(dst, src) +} +func (m *PublicCertificate) XXX_Size() int { + return xxx_messageInfo_PublicCertificate.Size(m) +} +func (m *PublicCertificate) XXX_DiscardUnknown() { + xxx_messageInfo_PublicCertificate.DiscardUnknown(m) +} + +var xxx_messageInfo_PublicCertificate proto.InternalMessageInfo + +func (m *PublicCertificate) GetKeyName() string { + if m != nil && m.KeyName != nil { + return *m.KeyName + } + return "" +} + +func (m *PublicCertificate) GetX509CertificatePem() string { + if m != nil && m.X509CertificatePem != nil { + return *m.X509CertificatePem + } + return "" +} + +type GetPublicCertificateForAppResponse struct { + PublicCertificateList []*PublicCertificate `protobuf:"bytes,1,rep,name=public_certificate_list,json=publicCertificateList" json:"public_certificate_list,omitempty"` + MaxClientCacheTimeInSecond *int64 `protobuf:"varint,2,opt,name=max_client_cache_time_in_second,json=maxClientCacheTimeInSecond" json:"max_client_cache_time_in_second,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetPublicCertificateForAppResponse) Reset() { *m = GetPublicCertificateForAppResponse{} } +func (m *GetPublicCertificateForAppResponse) String() string { return proto.CompactTextString(m) } +func (*GetPublicCertificateForAppResponse) ProtoMessage() {} +func (*GetPublicCertificateForAppResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_app_identity_service_08a6e3f74b04cfa4, []int{5} +} +func (m *GetPublicCertificateForAppResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetPublicCertificateForAppResponse.Unmarshal(m, b) +} +func (m *GetPublicCertificateForAppResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetPublicCertificateForAppResponse.Marshal(b, m, deterministic) +} +func (dst *GetPublicCertificateForAppResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetPublicCertificateForAppResponse.Merge(dst, src) +} +func (m *GetPublicCertificateForAppResponse) XXX_Size() int { + return xxx_messageInfo_GetPublicCertificateForAppResponse.Size(m) +} +func (m *GetPublicCertificateForAppResponse) XXX_DiscardUnknown() { + xxx_messageInfo_GetPublicCertificateForAppResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_GetPublicCertificateForAppResponse proto.InternalMessageInfo + +func (m *GetPublicCertificateForAppResponse) GetPublicCertificateList() []*PublicCertificate { + if m != nil { + return m.PublicCertificateList + } + return nil +} + +func (m *GetPublicCertificateForAppResponse) GetMaxClientCacheTimeInSecond() int64 { + if m != nil && m.MaxClientCacheTimeInSecond != nil { + return *m.MaxClientCacheTimeInSecond + } + return 0 +} + +type GetServiceAccountNameRequest struct { + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetServiceAccountNameRequest) Reset() { *m = GetServiceAccountNameRequest{} } +func (m *GetServiceAccountNameRequest) String() string { return proto.CompactTextString(m) } +func (*GetServiceAccountNameRequest) ProtoMessage() {} +func (*GetServiceAccountNameRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_app_identity_service_08a6e3f74b04cfa4, []int{6} +} +func (m *GetServiceAccountNameRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetServiceAccountNameRequest.Unmarshal(m, b) +} +func (m *GetServiceAccountNameRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetServiceAccountNameRequest.Marshal(b, m, deterministic) +} +func (dst *GetServiceAccountNameRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetServiceAccountNameRequest.Merge(dst, src) +} +func (m *GetServiceAccountNameRequest) XXX_Size() int { + return xxx_messageInfo_GetServiceAccountNameRequest.Size(m) +} +func (m *GetServiceAccountNameRequest) XXX_DiscardUnknown() { + xxx_messageInfo_GetServiceAccountNameRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_GetServiceAccountNameRequest proto.InternalMessageInfo + +type GetServiceAccountNameResponse struct { + ServiceAccountName *string `protobuf:"bytes,1,opt,name=service_account_name,json=serviceAccountName" json:"service_account_name,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetServiceAccountNameResponse) Reset() { *m = GetServiceAccountNameResponse{} } +func (m *GetServiceAccountNameResponse) String() string { return proto.CompactTextString(m) } +func (*GetServiceAccountNameResponse) ProtoMessage() {} +func (*GetServiceAccountNameResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_app_identity_service_08a6e3f74b04cfa4, []int{7} +} +func (m *GetServiceAccountNameResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetServiceAccountNameResponse.Unmarshal(m, b) +} +func (m *GetServiceAccountNameResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetServiceAccountNameResponse.Marshal(b, m, deterministic) +} +func (dst *GetServiceAccountNameResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetServiceAccountNameResponse.Merge(dst, src) +} +func (m *GetServiceAccountNameResponse) XXX_Size() int { + return xxx_messageInfo_GetServiceAccountNameResponse.Size(m) +} +func (m *GetServiceAccountNameResponse) XXX_DiscardUnknown() { + xxx_messageInfo_GetServiceAccountNameResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_GetServiceAccountNameResponse proto.InternalMessageInfo + +func (m *GetServiceAccountNameResponse) GetServiceAccountName() string { + if m != nil && m.ServiceAccountName != nil { + return *m.ServiceAccountName + } + return "" +} + +type GetAccessTokenRequest struct { + Scope []string `protobuf:"bytes,1,rep,name=scope" json:"scope,omitempty"` + ServiceAccountId *int64 `protobuf:"varint,2,opt,name=service_account_id,json=serviceAccountId" json:"service_account_id,omitempty"` + ServiceAccountName *string `protobuf:"bytes,3,opt,name=service_account_name,json=serviceAccountName" json:"service_account_name,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetAccessTokenRequest) Reset() { *m = GetAccessTokenRequest{} } +func (m *GetAccessTokenRequest) String() string { return proto.CompactTextString(m) } +func (*GetAccessTokenRequest) ProtoMessage() {} +func (*GetAccessTokenRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_app_identity_service_08a6e3f74b04cfa4, []int{8} +} +func (m *GetAccessTokenRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetAccessTokenRequest.Unmarshal(m, b) +} +func (m *GetAccessTokenRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetAccessTokenRequest.Marshal(b, m, deterministic) +} +func (dst *GetAccessTokenRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetAccessTokenRequest.Merge(dst, src) +} +func (m *GetAccessTokenRequest) XXX_Size() int { + return xxx_messageInfo_GetAccessTokenRequest.Size(m) +} +func (m *GetAccessTokenRequest) XXX_DiscardUnknown() { + xxx_messageInfo_GetAccessTokenRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_GetAccessTokenRequest proto.InternalMessageInfo + +func (m *GetAccessTokenRequest) GetScope() []string { + if m != nil { + return m.Scope + } + return nil +} + +func (m *GetAccessTokenRequest) GetServiceAccountId() int64 { + if m != nil && m.ServiceAccountId != nil { + return *m.ServiceAccountId + } + return 0 +} + +func (m *GetAccessTokenRequest) GetServiceAccountName() string { + if m != nil && m.ServiceAccountName != nil { + return *m.ServiceAccountName + } + return "" +} + +type GetAccessTokenResponse struct { + AccessToken *string `protobuf:"bytes,1,opt,name=access_token,json=accessToken" json:"access_token,omitempty"` + ExpirationTime *int64 `protobuf:"varint,2,opt,name=expiration_time,json=expirationTime" json:"expiration_time,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetAccessTokenResponse) Reset() { *m = GetAccessTokenResponse{} } +func (m *GetAccessTokenResponse) String() string { return proto.CompactTextString(m) } +func (*GetAccessTokenResponse) ProtoMessage() {} +func (*GetAccessTokenResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_app_identity_service_08a6e3f74b04cfa4, []int{9} +} +func (m *GetAccessTokenResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetAccessTokenResponse.Unmarshal(m, b) +} +func (m *GetAccessTokenResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetAccessTokenResponse.Marshal(b, m, deterministic) +} +func (dst *GetAccessTokenResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetAccessTokenResponse.Merge(dst, src) +} +func (m *GetAccessTokenResponse) XXX_Size() int { + return xxx_messageInfo_GetAccessTokenResponse.Size(m) +} +func (m *GetAccessTokenResponse) XXX_DiscardUnknown() { + xxx_messageInfo_GetAccessTokenResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_GetAccessTokenResponse proto.InternalMessageInfo + +func (m *GetAccessTokenResponse) GetAccessToken() string { + if m != nil && m.AccessToken != nil { + return *m.AccessToken + } + return "" +} + +func (m *GetAccessTokenResponse) GetExpirationTime() int64 { + if m != nil && m.ExpirationTime != nil { + return *m.ExpirationTime + } + return 0 +} + +type GetDefaultGcsBucketNameRequest struct { + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetDefaultGcsBucketNameRequest) Reset() { *m = GetDefaultGcsBucketNameRequest{} } +func (m *GetDefaultGcsBucketNameRequest) String() string { return proto.CompactTextString(m) } +func (*GetDefaultGcsBucketNameRequest) ProtoMessage() {} +func (*GetDefaultGcsBucketNameRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_app_identity_service_08a6e3f74b04cfa4, []int{10} +} +func (m *GetDefaultGcsBucketNameRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetDefaultGcsBucketNameRequest.Unmarshal(m, b) +} +func (m *GetDefaultGcsBucketNameRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetDefaultGcsBucketNameRequest.Marshal(b, m, deterministic) +} +func (dst *GetDefaultGcsBucketNameRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetDefaultGcsBucketNameRequest.Merge(dst, src) +} +func (m *GetDefaultGcsBucketNameRequest) XXX_Size() int { + return xxx_messageInfo_GetDefaultGcsBucketNameRequest.Size(m) +} +func (m *GetDefaultGcsBucketNameRequest) XXX_DiscardUnknown() { + xxx_messageInfo_GetDefaultGcsBucketNameRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_GetDefaultGcsBucketNameRequest proto.InternalMessageInfo + +type GetDefaultGcsBucketNameResponse struct { + DefaultGcsBucketName *string `protobuf:"bytes,1,opt,name=default_gcs_bucket_name,json=defaultGcsBucketName" json:"default_gcs_bucket_name,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetDefaultGcsBucketNameResponse) Reset() { *m = GetDefaultGcsBucketNameResponse{} } +func (m *GetDefaultGcsBucketNameResponse) String() string { return proto.CompactTextString(m) } +func (*GetDefaultGcsBucketNameResponse) ProtoMessage() {} +func (*GetDefaultGcsBucketNameResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_app_identity_service_08a6e3f74b04cfa4, []int{11} +} +func (m *GetDefaultGcsBucketNameResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetDefaultGcsBucketNameResponse.Unmarshal(m, b) +} +func (m *GetDefaultGcsBucketNameResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetDefaultGcsBucketNameResponse.Marshal(b, m, deterministic) +} +func (dst *GetDefaultGcsBucketNameResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetDefaultGcsBucketNameResponse.Merge(dst, src) +} +func (m *GetDefaultGcsBucketNameResponse) XXX_Size() int { + return xxx_messageInfo_GetDefaultGcsBucketNameResponse.Size(m) +} +func (m *GetDefaultGcsBucketNameResponse) XXX_DiscardUnknown() { + xxx_messageInfo_GetDefaultGcsBucketNameResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_GetDefaultGcsBucketNameResponse proto.InternalMessageInfo + +func (m *GetDefaultGcsBucketNameResponse) GetDefaultGcsBucketName() string { + if m != nil && m.DefaultGcsBucketName != nil { + return *m.DefaultGcsBucketName + } + return "" +} + +func init() { + proto.RegisterType((*AppIdentityServiceError)(nil), "appengine.AppIdentityServiceError") + proto.RegisterType((*SignForAppRequest)(nil), "appengine.SignForAppRequest") + proto.RegisterType((*SignForAppResponse)(nil), "appengine.SignForAppResponse") + proto.RegisterType((*GetPublicCertificateForAppRequest)(nil), "appengine.GetPublicCertificateForAppRequest") + proto.RegisterType((*PublicCertificate)(nil), "appengine.PublicCertificate") + proto.RegisterType((*GetPublicCertificateForAppResponse)(nil), "appengine.GetPublicCertificateForAppResponse") + proto.RegisterType((*GetServiceAccountNameRequest)(nil), "appengine.GetServiceAccountNameRequest") + proto.RegisterType((*GetServiceAccountNameResponse)(nil), "appengine.GetServiceAccountNameResponse") + proto.RegisterType((*GetAccessTokenRequest)(nil), "appengine.GetAccessTokenRequest") + proto.RegisterType((*GetAccessTokenResponse)(nil), "appengine.GetAccessTokenResponse") + proto.RegisterType((*GetDefaultGcsBucketNameRequest)(nil), "appengine.GetDefaultGcsBucketNameRequest") + proto.RegisterType((*GetDefaultGcsBucketNameResponse)(nil), "appengine.GetDefaultGcsBucketNameResponse") +} + +func init() { + proto.RegisterFile("google.golang.org/appengine/internal/app_identity/app_identity_service.proto", fileDescriptor_app_identity_service_08a6e3f74b04cfa4) +} + +var fileDescriptor_app_identity_service_08a6e3f74b04cfa4 = []byte{ + // 676 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x54, 0xdb, 0x6e, 0xda, 0x58, + 0x14, 0x1d, 0x26, 0x1a, 0x31, 0x6c, 0x12, 0x62, 0xce, 0x90, 0xcb, 0x8c, 0x32, 0xb9, 0x78, 0x1e, + 0x26, 0x0f, 0x15, 0x89, 0x2a, 0x45, 0x55, 0x1f, 0x8d, 0xed, 0x22, 0x54, 0x07, 0x53, 0x43, 0x9a, + 0xa8, 0x2f, 0xa7, 0xce, 0x61, 0xc7, 0x3d, 0x02, 0x9f, 0xe3, 0xda, 0x87, 0x0a, 0x3e, 0xa2, 0x3f, + 0xd2, 0x9f, 0xe8, 0x5b, 0xbf, 0xa5, 0x17, 0xb5, 0xdf, 0x50, 0xd9, 0x38, 0x5c, 0x92, 0x92, 0x37, + 0xbc, 0xf6, 0x5a, 0xcb, 0x6b, 0x2f, 0x6d, 0x0c, 0x4e, 0x20, 0x65, 0x30, 0xc4, 0x7a, 0x20, 0x87, + 0xbe, 0x08, 0xea, 0x32, 0x0e, 0x4e, 0xfc, 0x28, 0x42, 0x11, 0x70, 0x81, 0x27, 0x5c, 0x28, 0x8c, + 0x85, 0x3f, 0x4c, 0x21, 0xca, 0xfb, 0x28, 0x14, 0x57, 0x93, 0xa5, 0x07, 0x9a, 0x60, 0xfc, 0x8e, + 0x33, 0xac, 0x47, 0xb1, 0x54, 0x92, 0x94, 0x66, 0x5a, 0xfd, 0x53, 0x01, 0x76, 0x8c, 0x28, 0x6a, + 0xe5, 0xc4, 0xee, 0x94, 0x67, 0xc7, 0xb1, 0x8c, 0xf5, 0x0f, 0x05, 0x28, 0x65, 0xbf, 0x4c, 0xd9, + 0x47, 0x52, 0x86, 0x62, 0xf7, 0xc2, 0x34, 0xed, 0x6e, 0x57, 0xfb, 0x8d, 0x54, 0x61, 0xe3, 0xa2, + 0xfd, 0xbc, 0xed, 0x5e, 0xb6, 0x69, 0xd7, 0x74, 0x3b, 0xb6, 0x56, 0x22, 0x7f, 0x41, 0xa5, 0xe1, + 0xb8, 0x0d, 0xda, 0x73, 0x5d, 0xea, 0x18, 0x5e, 0xd3, 0xd6, 0x3e, 0x17, 0xc9, 0x36, 0x54, 0x2d, + 0xdb, 0xb0, 0x9c, 0x56, 0xdb, 0xa6, 0xf6, 0x95, 0x69, 0xdb, 0x96, 0x6d, 0x69, 0x5f, 0x8a, 0xa4, + 0x06, 0x9b, 0x6d, 0xb7, 0x47, 0x0d, 0xfa, 0xd2, 0x70, 0x5a, 0x16, 0x35, 0x3a, 0x1d, 0xed, 0x6b, + 0x91, 0x90, 0xb9, 0xab, 0xed, 0x79, 0xae, 0xa7, 0x7d, 0x2b, 0x12, 0x0d, 0xca, 0x19, 0xd3, 0x71, + 0xdc, 0x4b, 0xdb, 0xd2, 0xbe, 0xcf, 0xb4, 0xad, 0xf3, 0x8e, 0x63, 0x9f, 0xdb, 0xed, 0x9e, 0x6d, + 0x69, 0x3f, 0x8a, 0xfa, 0x13, 0xa8, 0x76, 0x79, 0x20, 0x9e, 0xc9, 0xd8, 0x88, 0x22, 0x0f, 0xdf, + 0x8e, 0x30, 0x51, 0x44, 0x87, 0x8d, 0xeb, 0x89, 0xc2, 0x84, 0x2a, 0x49, 0x13, 0x1e, 0x88, 0xdd, + 0xc2, 0x61, 0xe1, 0x78, 0xdd, 0x2b, 0x67, 0x60, 0x4f, 0xa6, 0x02, 0xfd, 0x0a, 0xc8, 0xa2, 0x30, + 0x89, 0xa4, 0x48, 0x90, 0xfc, 0x0d, 0x7f, 0x0e, 0x70, 0x42, 0x85, 0x1f, 0x62, 0x26, 0x2a, 0x79, + 0xc5, 0x01, 0x4e, 0xda, 0x7e, 0x88, 0xe4, 0x7f, 0xd8, 0x4c, 0xbd, 0x7c, 0x35, 0x8a, 0x91, 0x66, + 0x4e, 0xbb, 0xbf, 0x67, 0xb6, 0x95, 0x19, 0xdc, 0x48, 0x51, 0xfd, 0x3f, 0x38, 0x6a, 0xa2, 0xea, + 0x8c, 0xae, 0x87, 0x9c, 0x99, 0x18, 0x2b, 0x7e, 0xc3, 0x99, 0xaf, 0x70, 0x29, 0xa2, 0xfe, 0x1a, + 0xaa, 0xf7, 0x18, 0x0f, 0xbd, 0xfd, 0x14, 0x6a, 0xe3, 0xb3, 0xd3, 0xa7, 0x94, 0xcd, 0xe9, 0x34, + 0xc2, 0x30, 0x8b, 0x50, 0xf2, 0x48, 0x3a, 0x5b, 0x70, 0xea, 0x60, 0xa8, 0x7f, 0x2c, 0x80, 0xfe, + 0x50, 0x8e, 0x7c, 0xe3, 0x1e, 0xec, 0x44, 0x19, 0x65, 0xc9, 0x7a, 0xc8, 0x13, 0xb5, 0x5b, 0x38, + 0x5c, 0x3b, 0x2e, 0x3f, 0xde, 0xab, 0xcf, 0xce, 0xa6, 0x7e, 0xcf, 0xcc, 0xdb, 0x8a, 0xee, 0x42, + 0x0e, 0x4f, 0x14, 0x31, 0xe1, 0x20, 0xf4, 0xc7, 0x94, 0x0d, 0x39, 0x0a, 0x45, 0x99, 0xcf, 0xde, + 0x20, 0x55, 0x3c, 0x44, 0xca, 0x05, 0x4d, 0x90, 0x49, 0xd1, 0xcf, 0x92, 0xaf, 0x79, 0xff, 0x84, + 0xfe, 0xd8, 0xcc, 0x58, 0x66, 0x4a, 0xea, 0xf1, 0x10, 0x5b, 0xa2, 0x9b, 0x31, 0xf4, 0x7d, 0xd8, + 0x6b, 0xa2, 0xca, 0x6f, 0xd3, 0x60, 0x4c, 0x8e, 0x84, 0x4a, 0xcb, 0xb8, 0xed, 0xf0, 0x05, 0xfc, + 0xbb, 0x62, 0x9e, 0xef, 0x76, 0x0a, 0xb5, 0xfc, 0x1f, 0x40, 0xfd, 0xe9, 0x78, 0xb1, 0x5b, 0x92, + 0xdc, 0x53, 0xea, 0xef, 0x0b, 0xb0, 0xd5, 0x44, 0x65, 0x30, 0x86, 0x49, 0xd2, 0x93, 0x03, 0x14, + 0xb7, 0x37, 0x55, 0x83, 0x3f, 0x12, 0x26, 0x23, 0xcc, 0x5a, 0x29, 0x79, 0xd3, 0x07, 0xf2, 0x08, + 0xc8, 0xdd, 0x37, 0xf0, 0xdb, 0xd5, 0xb4, 0x65, 0xff, 0x56, 0x7f, 0x65, 0x9e, 0xb5, 0x95, 0x79, + 0xfa, 0xb0, 0x7d, 0x37, 0x4e, 0xbe, 0xdb, 0x11, 0xac, 0xfb, 0x19, 0x4c, 0x55, 0x8a, 0xe7, 0x3b, + 0x95, 0xfd, 0x39, 0x35, 0xbd, 0x58, 0x1c, 0x47, 0x3c, 0xf6, 0x15, 0x97, 0x22, 0xab, 0x3f, 0x4f, + 0x56, 0x99, 0xc3, 0x69, 0xe1, 0xfa, 0x21, 0xec, 0x37, 0x51, 0x59, 0x78, 0xe3, 0x8f, 0x86, 0xaa, + 0xc9, 0x92, 0xc6, 0x88, 0x0d, 0x70, 0xa9, 0xea, 0x2b, 0x38, 0x58, 0xc9, 0xc8, 0x03, 0x9d, 0xc1, + 0x4e, 0x7f, 0x3a, 0xa7, 0x01, 0x4b, 0xe8, 0x75, 0xc6, 0x58, 0xec, 0xbb, 0xd6, 0xff, 0x85, 0xbc, + 0x51, 0x79, 0xb5, 0xbe, 0xf8, 0xc9, 0xfa, 0x19, 0x00, 0x00, 0xff, 0xff, 0x37, 0x4c, 0x56, 0x38, + 0xf3, 0x04, 0x00, 0x00, +} diff --git a/vendor/google.golang.org/appengine/internal/app_identity/app_identity_service.proto b/vendor/google.golang.org/appengine/internal/app_identity/app_identity_service.proto new file mode 100644 index 00000000..19610ca5 --- /dev/null +++ b/vendor/google.golang.org/appengine/internal/app_identity/app_identity_service.proto @@ -0,0 +1,64 @@ +syntax = "proto2"; +option go_package = "app_identity"; + +package appengine; + +message AppIdentityServiceError { + enum ErrorCode { + SUCCESS = 0; + UNKNOWN_SCOPE = 9; + BLOB_TOO_LARGE = 1000; + DEADLINE_EXCEEDED = 1001; + NOT_A_VALID_APP = 1002; + UNKNOWN_ERROR = 1003; + NOT_ALLOWED = 1005; + NOT_IMPLEMENTED = 1006; + } +} + +message SignForAppRequest { + optional bytes bytes_to_sign = 1; +} + +message SignForAppResponse { + optional string key_name = 1; + optional bytes signature_bytes = 2; +} + +message GetPublicCertificateForAppRequest { +} + +message PublicCertificate { + optional string key_name = 1; + optional string x509_certificate_pem = 2; +} + +message GetPublicCertificateForAppResponse { + repeated PublicCertificate public_certificate_list = 1; + optional int64 max_client_cache_time_in_second = 2; +} + +message GetServiceAccountNameRequest { +} + +message GetServiceAccountNameResponse { + optional string service_account_name = 1; +} + +message GetAccessTokenRequest { + repeated string scope = 1; + optional int64 service_account_id = 2; + optional string service_account_name = 3; +} + +message GetAccessTokenResponse { + optional string access_token = 1; + optional int64 expiration_time = 2; +} + +message GetDefaultGcsBucketNameRequest { +} + +message GetDefaultGcsBucketNameResponse { + optional string default_gcs_bucket_name = 1; +} diff --git a/vendor/google.golang.org/appengine/internal/modules/modules_service.pb.go b/vendor/google.golang.org/appengine/internal/modules/modules_service.pb.go new file mode 100644 index 00000000..ddfc0c04 --- /dev/null +++ b/vendor/google.golang.org/appengine/internal/modules/modules_service.pb.go @@ -0,0 +1,786 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: google.golang.org/appengine/internal/modules/modules_service.proto + +package modules + +import proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package + +type ModulesServiceError_ErrorCode int32 + +const ( + ModulesServiceError_OK ModulesServiceError_ErrorCode = 0 + ModulesServiceError_INVALID_MODULE ModulesServiceError_ErrorCode = 1 + ModulesServiceError_INVALID_VERSION ModulesServiceError_ErrorCode = 2 + ModulesServiceError_INVALID_INSTANCES ModulesServiceError_ErrorCode = 3 + ModulesServiceError_TRANSIENT_ERROR ModulesServiceError_ErrorCode = 4 + ModulesServiceError_UNEXPECTED_STATE ModulesServiceError_ErrorCode = 5 +) + +var ModulesServiceError_ErrorCode_name = map[int32]string{ + 0: "OK", + 1: "INVALID_MODULE", + 2: "INVALID_VERSION", + 3: "INVALID_INSTANCES", + 4: "TRANSIENT_ERROR", + 5: "UNEXPECTED_STATE", +} +var ModulesServiceError_ErrorCode_value = map[string]int32{ + "OK": 0, + "INVALID_MODULE": 1, + "INVALID_VERSION": 2, + "INVALID_INSTANCES": 3, + "TRANSIENT_ERROR": 4, + "UNEXPECTED_STATE": 5, +} + +func (x ModulesServiceError_ErrorCode) Enum() *ModulesServiceError_ErrorCode { + p := new(ModulesServiceError_ErrorCode) + *p = x + return p +} +func (x ModulesServiceError_ErrorCode) String() string { + return proto.EnumName(ModulesServiceError_ErrorCode_name, int32(x)) +} +func (x *ModulesServiceError_ErrorCode) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(ModulesServiceError_ErrorCode_value, data, "ModulesServiceError_ErrorCode") + if err != nil { + return err + } + *x = ModulesServiceError_ErrorCode(value) + return nil +} +func (ModulesServiceError_ErrorCode) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{0, 0} +} + +type ModulesServiceError struct { + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ModulesServiceError) Reset() { *m = ModulesServiceError{} } +func (m *ModulesServiceError) String() string { return proto.CompactTextString(m) } +func (*ModulesServiceError) ProtoMessage() {} +func (*ModulesServiceError) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{0} +} +func (m *ModulesServiceError) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ModulesServiceError.Unmarshal(m, b) +} +func (m *ModulesServiceError) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ModulesServiceError.Marshal(b, m, deterministic) +} +func (dst *ModulesServiceError) XXX_Merge(src proto.Message) { + xxx_messageInfo_ModulesServiceError.Merge(dst, src) +} +func (m *ModulesServiceError) XXX_Size() int { + return xxx_messageInfo_ModulesServiceError.Size(m) +} +func (m *ModulesServiceError) XXX_DiscardUnknown() { + xxx_messageInfo_ModulesServiceError.DiscardUnknown(m) +} + +var xxx_messageInfo_ModulesServiceError proto.InternalMessageInfo + +type GetModulesRequest struct { + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetModulesRequest) Reset() { *m = GetModulesRequest{} } +func (m *GetModulesRequest) String() string { return proto.CompactTextString(m) } +func (*GetModulesRequest) ProtoMessage() {} +func (*GetModulesRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{1} +} +func (m *GetModulesRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetModulesRequest.Unmarshal(m, b) +} +func (m *GetModulesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetModulesRequest.Marshal(b, m, deterministic) +} +func (dst *GetModulesRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetModulesRequest.Merge(dst, src) +} +func (m *GetModulesRequest) XXX_Size() int { + return xxx_messageInfo_GetModulesRequest.Size(m) +} +func (m *GetModulesRequest) XXX_DiscardUnknown() { + xxx_messageInfo_GetModulesRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_GetModulesRequest proto.InternalMessageInfo + +type GetModulesResponse struct { + Module []string `protobuf:"bytes,1,rep,name=module" json:"module,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetModulesResponse) Reset() { *m = GetModulesResponse{} } +func (m *GetModulesResponse) String() string { return proto.CompactTextString(m) } +func (*GetModulesResponse) ProtoMessage() {} +func (*GetModulesResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{2} +} +func (m *GetModulesResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetModulesResponse.Unmarshal(m, b) +} +func (m *GetModulesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetModulesResponse.Marshal(b, m, deterministic) +} +func (dst *GetModulesResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetModulesResponse.Merge(dst, src) +} +func (m *GetModulesResponse) XXX_Size() int { + return xxx_messageInfo_GetModulesResponse.Size(m) +} +func (m *GetModulesResponse) XXX_DiscardUnknown() { + xxx_messageInfo_GetModulesResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_GetModulesResponse proto.InternalMessageInfo + +func (m *GetModulesResponse) GetModule() []string { + if m != nil { + return m.Module + } + return nil +} + +type GetVersionsRequest struct { + Module *string `protobuf:"bytes,1,opt,name=module" json:"module,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetVersionsRequest) Reset() { *m = GetVersionsRequest{} } +func (m *GetVersionsRequest) String() string { return proto.CompactTextString(m) } +func (*GetVersionsRequest) ProtoMessage() {} +func (*GetVersionsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{3} +} +func (m *GetVersionsRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetVersionsRequest.Unmarshal(m, b) +} +func (m *GetVersionsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetVersionsRequest.Marshal(b, m, deterministic) +} +func (dst *GetVersionsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetVersionsRequest.Merge(dst, src) +} +func (m *GetVersionsRequest) XXX_Size() int { + return xxx_messageInfo_GetVersionsRequest.Size(m) +} +func (m *GetVersionsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_GetVersionsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_GetVersionsRequest proto.InternalMessageInfo + +func (m *GetVersionsRequest) GetModule() string { + if m != nil && m.Module != nil { + return *m.Module + } + return "" +} + +type GetVersionsResponse struct { + Version []string `protobuf:"bytes,1,rep,name=version" json:"version,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetVersionsResponse) Reset() { *m = GetVersionsResponse{} } +func (m *GetVersionsResponse) String() string { return proto.CompactTextString(m) } +func (*GetVersionsResponse) ProtoMessage() {} +func (*GetVersionsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{4} +} +func (m *GetVersionsResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetVersionsResponse.Unmarshal(m, b) +} +func (m *GetVersionsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetVersionsResponse.Marshal(b, m, deterministic) +} +func (dst *GetVersionsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetVersionsResponse.Merge(dst, src) +} +func (m *GetVersionsResponse) XXX_Size() int { + return xxx_messageInfo_GetVersionsResponse.Size(m) +} +func (m *GetVersionsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_GetVersionsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_GetVersionsResponse proto.InternalMessageInfo + +func (m *GetVersionsResponse) GetVersion() []string { + if m != nil { + return m.Version + } + return nil +} + +type GetDefaultVersionRequest struct { + Module *string `protobuf:"bytes,1,opt,name=module" json:"module,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetDefaultVersionRequest) Reset() { *m = GetDefaultVersionRequest{} } +func (m *GetDefaultVersionRequest) String() string { return proto.CompactTextString(m) } +func (*GetDefaultVersionRequest) ProtoMessage() {} +func (*GetDefaultVersionRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{5} +} +func (m *GetDefaultVersionRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetDefaultVersionRequest.Unmarshal(m, b) +} +func (m *GetDefaultVersionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetDefaultVersionRequest.Marshal(b, m, deterministic) +} +func (dst *GetDefaultVersionRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetDefaultVersionRequest.Merge(dst, src) +} +func (m *GetDefaultVersionRequest) XXX_Size() int { + return xxx_messageInfo_GetDefaultVersionRequest.Size(m) +} +func (m *GetDefaultVersionRequest) XXX_DiscardUnknown() { + xxx_messageInfo_GetDefaultVersionRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_GetDefaultVersionRequest proto.InternalMessageInfo + +func (m *GetDefaultVersionRequest) GetModule() string { + if m != nil && m.Module != nil { + return *m.Module + } + return "" +} + +type GetDefaultVersionResponse struct { + Version *string `protobuf:"bytes,1,req,name=version" json:"version,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetDefaultVersionResponse) Reset() { *m = GetDefaultVersionResponse{} } +func (m *GetDefaultVersionResponse) String() string { return proto.CompactTextString(m) } +func (*GetDefaultVersionResponse) ProtoMessage() {} +func (*GetDefaultVersionResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{6} +} +func (m *GetDefaultVersionResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetDefaultVersionResponse.Unmarshal(m, b) +} +func (m *GetDefaultVersionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetDefaultVersionResponse.Marshal(b, m, deterministic) +} +func (dst *GetDefaultVersionResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetDefaultVersionResponse.Merge(dst, src) +} +func (m *GetDefaultVersionResponse) XXX_Size() int { + return xxx_messageInfo_GetDefaultVersionResponse.Size(m) +} +func (m *GetDefaultVersionResponse) XXX_DiscardUnknown() { + xxx_messageInfo_GetDefaultVersionResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_GetDefaultVersionResponse proto.InternalMessageInfo + +func (m *GetDefaultVersionResponse) GetVersion() string { + if m != nil && m.Version != nil { + return *m.Version + } + return "" +} + +type GetNumInstancesRequest struct { + Module *string `protobuf:"bytes,1,opt,name=module" json:"module,omitempty"` + Version *string `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetNumInstancesRequest) Reset() { *m = GetNumInstancesRequest{} } +func (m *GetNumInstancesRequest) String() string { return proto.CompactTextString(m) } +func (*GetNumInstancesRequest) ProtoMessage() {} +func (*GetNumInstancesRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{7} +} +func (m *GetNumInstancesRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetNumInstancesRequest.Unmarshal(m, b) +} +func (m *GetNumInstancesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetNumInstancesRequest.Marshal(b, m, deterministic) +} +func (dst *GetNumInstancesRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetNumInstancesRequest.Merge(dst, src) +} +func (m *GetNumInstancesRequest) XXX_Size() int { + return xxx_messageInfo_GetNumInstancesRequest.Size(m) +} +func (m *GetNumInstancesRequest) XXX_DiscardUnknown() { + xxx_messageInfo_GetNumInstancesRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_GetNumInstancesRequest proto.InternalMessageInfo + +func (m *GetNumInstancesRequest) GetModule() string { + if m != nil && m.Module != nil { + return *m.Module + } + return "" +} + +func (m *GetNumInstancesRequest) GetVersion() string { + if m != nil && m.Version != nil { + return *m.Version + } + return "" +} + +type GetNumInstancesResponse struct { + Instances *int64 `protobuf:"varint,1,req,name=instances" json:"instances,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetNumInstancesResponse) Reset() { *m = GetNumInstancesResponse{} } +func (m *GetNumInstancesResponse) String() string { return proto.CompactTextString(m) } +func (*GetNumInstancesResponse) ProtoMessage() {} +func (*GetNumInstancesResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{8} +} +func (m *GetNumInstancesResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetNumInstancesResponse.Unmarshal(m, b) +} +func (m *GetNumInstancesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetNumInstancesResponse.Marshal(b, m, deterministic) +} +func (dst *GetNumInstancesResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetNumInstancesResponse.Merge(dst, src) +} +func (m *GetNumInstancesResponse) XXX_Size() int { + return xxx_messageInfo_GetNumInstancesResponse.Size(m) +} +func (m *GetNumInstancesResponse) XXX_DiscardUnknown() { + xxx_messageInfo_GetNumInstancesResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_GetNumInstancesResponse proto.InternalMessageInfo + +func (m *GetNumInstancesResponse) GetInstances() int64 { + if m != nil && m.Instances != nil { + return *m.Instances + } + return 0 +} + +type SetNumInstancesRequest struct { + Module *string `protobuf:"bytes,1,opt,name=module" json:"module,omitempty"` + Version *string `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"` + Instances *int64 `protobuf:"varint,3,req,name=instances" json:"instances,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *SetNumInstancesRequest) Reset() { *m = SetNumInstancesRequest{} } +func (m *SetNumInstancesRequest) String() string { return proto.CompactTextString(m) } +func (*SetNumInstancesRequest) ProtoMessage() {} +func (*SetNumInstancesRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{9} +} +func (m *SetNumInstancesRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_SetNumInstancesRequest.Unmarshal(m, b) +} +func (m *SetNumInstancesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_SetNumInstancesRequest.Marshal(b, m, deterministic) +} +func (dst *SetNumInstancesRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_SetNumInstancesRequest.Merge(dst, src) +} +func (m *SetNumInstancesRequest) XXX_Size() int { + return xxx_messageInfo_SetNumInstancesRequest.Size(m) +} +func (m *SetNumInstancesRequest) XXX_DiscardUnknown() { + xxx_messageInfo_SetNumInstancesRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_SetNumInstancesRequest proto.InternalMessageInfo + +func (m *SetNumInstancesRequest) GetModule() string { + if m != nil && m.Module != nil { + return *m.Module + } + return "" +} + +func (m *SetNumInstancesRequest) GetVersion() string { + if m != nil && m.Version != nil { + return *m.Version + } + return "" +} + +func (m *SetNumInstancesRequest) GetInstances() int64 { + if m != nil && m.Instances != nil { + return *m.Instances + } + return 0 +} + +type SetNumInstancesResponse struct { + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *SetNumInstancesResponse) Reset() { *m = SetNumInstancesResponse{} } +func (m *SetNumInstancesResponse) String() string { return proto.CompactTextString(m) } +func (*SetNumInstancesResponse) ProtoMessage() {} +func (*SetNumInstancesResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{10} +} +func (m *SetNumInstancesResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_SetNumInstancesResponse.Unmarshal(m, b) +} +func (m *SetNumInstancesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_SetNumInstancesResponse.Marshal(b, m, deterministic) +} +func (dst *SetNumInstancesResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_SetNumInstancesResponse.Merge(dst, src) +} +func (m *SetNumInstancesResponse) XXX_Size() int { + return xxx_messageInfo_SetNumInstancesResponse.Size(m) +} +func (m *SetNumInstancesResponse) XXX_DiscardUnknown() { + xxx_messageInfo_SetNumInstancesResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_SetNumInstancesResponse proto.InternalMessageInfo + +type StartModuleRequest struct { + Module *string `protobuf:"bytes,1,req,name=module" json:"module,omitempty"` + Version *string `protobuf:"bytes,2,req,name=version" json:"version,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *StartModuleRequest) Reset() { *m = StartModuleRequest{} } +func (m *StartModuleRequest) String() string { return proto.CompactTextString(m) } +func (*StartModuleRequest) ProtoMessage() {} +func (*StartModuleRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{11} +} +func (m *StartModuleRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_StartModuleRequest.Unmarshal(m, b) +} +func (m *StartModuleRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_StartModuleRequest.Marshal(b, m, deterministic) +} +func (dst *StartModuleRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_StartModuleRequest.Merge(dst, src) +} +func (m *StartModuleRequest) XXX_Size() int { + return xxx_messageInfo_StartModuleRequest.Size(m) +} +func (m *StartModuleRequest) XXX_DiscardUnknown() { + xxx_messageInfo_StartModuleRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_StartModuleRequest proto.InternalMessageInfo + +func (m *StartModuleRequest) GetModule() string { + if m != nil && m.Module != nil { + return *m.Module + } + return "" +} + +func (m *StartModuleRequest) GetVersion() string { + if m != nil && m.Version != nil { + return *m.Version + } + return "" +} + +type StartModuleResponse struct { + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *StartModuleResponse) Reset() { *m = StartModuleResponse{} } +func (m *StartModuleResponse) String() string { return proto.CompactTextString(m) } +func (*StartModuleResponse) ProtoMessage() {} +func (*StartModuleResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{12} +} +func (m *StartModuleResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_StartModuleResponse.Unmarshal(m, b) +} +func (m *StartModuleResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_StartModuleResponse.Marshal(b, m, deterministic) +} +func (dst *StartModuleResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_StartModuleResponse.Merge(dst, src) +} +func (m *StartModuleResponse) XXX_Size() int { + return xxx_messageInfo_StartModuleResponse.Size(m) +} +func (m *StartModuleResponse) XXX_DiscardUnknown() { + xxx_messageInfo_StartModuleResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_StartModuleResponse proto.InternalMessageInfo + +type StopModuleRequest struct { + Module *string `protobuf:"bytes,1,opt,name=module" json:"module,omitempty"` + Version *string `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *StopModuleRequest) Reset() { *m = StopModuleRequest{} } +func (m *StopModuleRequest) String() string { return proto.CompactTextString(m) } +func (*StopModuleRequest) ProtoMessage() {} +func (*StopModuleRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{13} +} +func (m *StopModuleRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_StopModuleRequest.Unmarshal(m, b) +} +func (m *StopModuleRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_StopModuleRequest.Marshal(b, m, deterministic) +} +func (dst *StopModuleRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_StopModuleRequest.Merge(dst, src) +} +func (m *StopModuleRequest) XXX_Size() int { + return xxx_messageInfo_StopModuleRequest.Size(m) +} +func (m *StopModuleRequest) XXX_DiscardUnknown() { + xxx_messageInfo_StopModuleRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_StopModuleRequest proto.InternalMessageInfo + +func (m *StopModuleRequest) GetModule() string { + if m != nil && m.Module != nil { + return *m.Module + } + return "" +} + +func (m *StopModuleRequest) GetVersion() string { + if m != nil && m.Version != nil { + return *m.Version + } + return "" +} + +type StopModuleResponse struct { + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *StopModuleResponse) Reset() { *m = StopModuleResponse{} } +func (m *StopModuleResponse) String() string { return proto.CompactTextString(m) } +func (*StopModuleResponse) ProtoMessage() {} +func (*StopModuleResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{14} +} +func (m *StopModuleResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_StopModuleResponse.Unmarshal(m, b) +} +func (m *StopModuleResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_StopModuleResponse.Marshal(b, m, deterministic) +} +func (dst *StopModuleResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_StopModuleResponse.Merge(dst, src) +} +func (m *StopModuleResponse) XXX_Size() int { + return xxx_messageInfo_StopModuleResponse.Size(m) +} +func (m *StopModuleResponse) XXX_DiscardUnknown() { + xxx_messageInfo_StopModuleResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_StopModuleResponse proto.InternalMessageInfo + +type GetHostnameRequest struct { + Module *string `protobuf:"bytes,1,opt,name=module" json:"module,omitempty"` + Version *string `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"` + Instance *string `protobuf:"bytes,3,opt,name=instance" json:"instance,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetHostnameRequest) Reset() { *m = GetHostnameRequest{} } +func (m *GetHostnameRequest) String() string { return proto.CompactTextString(m) } +func (*GetHostnameRequest) ProtoMessage() {} +func (*GetHostnameRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{15} +} +func (m *GetHostnameRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetHostnameRequest.Unmarshal(m, b) +} +func (m *GetHostnameRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetHostnameRequest.Marshal(b, m, deterministic) +} +func (dst *GetHostnameRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetHostnameRequest.Merge(dst, src) +} +func (m *GetHostnameRequest) XXX_Size() int { + return xxx_messageInfo_GetHostnameRequest.Size(m) +} +func (m *GetHostnameRequest) XXX_DiscardUnknown() { + xxx_messageInfo_GetHostnameRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_GetHostnameRequest proto.InternalMessageInfo + +func (m *GetHostnameRequest) GetModule() string { + if m != nil && m.Module != nil { + return *m.Module + } + return "" +} + +func (m *GetHostnameRequest) GetVersion() string { + if m != nil && m.Version != nil { + return *m.Version + } + return "" +} + +func (m *GetHostnameRequest) GetInstance() string { + if m != nil && m.Instance != nil { + return *m.Instance + } + return "" +} + +type GetHostnameResponse struct { + Hostname *string `protobuf:"bytes,1,req,name=hostname" json:"hostname,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetHostnameResponse) Reset() { *m = GetHostnameResponse{} } +func (m *GetHostnameResponse) String() string { return proto.CompactTextString(m) } +func (*GetHostnameResponse) ProtoMessage() {} +func (*GetHostnameResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_modules_service_9cd3bffe4e91c59a, []int{16} +} +func (m *GetHostnameResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetHostnameResponse.Unmarshal(m, b) +} +func (m *GetHostnameResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetHostnameResponse.Marshal(b, m, deterministic) +} +func (dst *GetHostnameResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetHostnameResponse.Merge(dst, src) +} +func (m *GetHostnameResponse) XXX_Size() int { + return xxx_messageInfo_GetHostnameResponse.Size(m) +} +func (m *GetHostnameResponse) XXX_DiscardUnknown() { + xxx_messageInfo_GetHostnameResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_GetHostnameResponse proto.InternalMessageInfo + +func (m *GetHostnameResponse) GetHostname() string { + if m != nil && m.Hostname != nil { + return *m.Hostname + } + return "" +} + +func init() { + proto.RegisterType((*ModulesServiceError)(nil), "appengine.ModulesServiceError") + proto.RegisterType((*GetModulesRequest)(nil), "appengine.GetModulesRequest") + proto.RegisterType((*GetModulesResponse)(nil), "appengine.GetModulesResponse") + proto.RegisterType((*GetVersionsRequest)(nil), "appengine.GetVersionsRequest") + proto.RegisterType((*GetVersionsResponse)(nil), "appengine.GetVersionsResponse") + proto.RegisterType((*GetDefaultVersionRequest)(nil), "appengine.GetDefaultVersionRequest") + proto.RegisterType((*GetDefaultVersionResponse)(nil), "appengine.GetDefaultVersionResponse") + proto.RegisterType((*GetNumInstancesRequest)(nil), "appengine.GetNumInstancesRequest") + proto.RegisterType((*GetNumInstancesResponse)(nil), "appengine.GetNumInstancesResponse") + proto.RegisterType((*SetNumInstancesRequest)(nil), "appengine.SetNumInstancesRequest") + proto.RegisterType((*SetNumInstancesResponse)(nil), "appengine.SetNumInstancesResponse") + proto.RegisterType((*StartModuleRequest)(nil), "appengine.StartModuleRequest") + proto.RegisterType((*StartModuleResponse)(nil), "appengine.StartModuleResponse") + proto.RegisterType((*StopModuleRequest)(nil), "appengine.StopModuleRequest") + proto.RegisterType((*StopModuleResponse)(nil), "appengine.StopModuleResponse") + proto.RegisterType((*GetHostnameRequest)(nil), "appengine.GetHostnameRequest") + proto.RegisterType((*GetHostnameResponse)(nil), "appengine.GetHostnameResponse") +} + +func init() { + proto.RegisterFile("google.golang.org/appengine/internal/modules/modules_service.proto", fileDescriptor_modules_service_9cd3bffe4e91c59a) +} + +var fileDescriptor_modules_service_9cd3bffe4e91c59a = []byte{ + // 457 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x94, 0xc1, 0x6f, 0xd3, 0x30, + 0x14, 0xc6, 0x69, 0x02, 0xdb, 0xf2, 0x0e, 0x90, 0x3a, 0x5b, 0xd7, 0x4d, 0x1c, 0x50, 0x4e, 0x1c, + 0x50, 0x2b, 0x90, 0x10, 0xe7, 0xae, 0x35, 0x25, 0xb0, 0xa5, 0x28, 0xce, 0x2a, 0xc4, 0xa5, 0x0a, + 0xdb, 0x23, 0x8b, 0x94, 0xda, 0xc1, 0x76, 0x77, 0xe4, 0xbf, 0xe0, 0xff, 0x45, 0x4b, 0xed, 0xb6, + 0x81, 0x4e, 0x45, 0x68, 0xa7, 0xe4, 0x7d, 0xfe, 0xfc, 0x7b, 0x9f, 0x5f, 0xac, 0xc0, 0x59, 0x2e, + 0x44, 0x5e, 0x62, 0x2f, 0x17, 0x65, 0xc6, 0xf3, 0x9e, 0x90, 0x79, 0x3f, 0xab, 0x2a, 0xe4, 0x79, + 0xc1, 0xb1, 0x5f, 0x70, 0x8d, 0x92, 0x67, 0x65, 0x7f, 0x2e, 0xae, 0x17, 0x25, 0x2a, 0xfb, 0x9c, + 0x29, 0x94, 0xb7, 0xc5, 0x15, 0xf6, 0x2a, 0x29, 0xb4, 0x20, 0xde, 0x6a, 0x47, 0xf8, 0xab, 0x05, + 0xc1, 0xc5, 0xd2, 0xc4, 0x96, 0x1e, 0x2a, 0xa5, 0x90, 0xe1, 0x4f, 0xf0, 0xea, 0x97, 0xa1, 0xb8, + 0x46, 0xb2, 0x07, 0xce, 0xe4, 0x93, 0xff, 0x88, 0x10, 0x78, 0x1a, 0xc5, 0xd3, 0xc1, 0x79, 0x34, + 0x9a, 0x5d, 0x4c, 0x46, 0x97, 0xe7, 0xd4, 0x6f, 0x91, 0x00, 0x9e, 0x59, 0x6d, 0x4a, 0x13, 0x16, + 0x4d, 0x62, 0xdf, 0x21, 0x47, 0xd0, 0xb6, 0x62, 0x14, 0xb3, 0x74, 0x10, 0x0f, 0x29, 0xf3, 0xdd, + 0x3b, 0x6f, 0x9a, 0x0c, 0x62, 0x16, 0xd1, 0x38, 0x9d, 0xd1, 0x24, 0x99, 0x24, 0xfe, 0x63, 0x72, + 0x08, 0xfe, 0x65, 0x4c, 0xbf, 0x7c, 0xa6, 0xc3, 0x94, 0x8e, 0x66, 0x2c, 0x1d, 0xa4, 0xd4, 0x7f, + 0x12, 0x06, 0xd0, 0x1e, 0xa3, 0x36, 0xc9, 0x12, 0xfc, 0xb1, 0x40, 0xa5, 0xc3, 0x57, 0x40, 0x36, + 0x45, 0x55, 0x09, 0xae, 0x90, 0x74, 0x60, 0x6f, 0x79, 0xcc, 0x6e, 0xeb, 0x85, 0xfb, 0xd2, 0x4b, + 0x4c, 0x65, 0xdc, 0x53, 0x94, 0xaa, 0x10, 0xdc, 0x32, 0x1a, 0xee, 0xd6, 0x86, 0xbb, 0x0f, 0x41, + 0xc3, 0x6d, 0xe0, 0x5d, 0xd8, 0xbf, 0x5d, 0x6a, 0x86, 0x6e, 0xcb, 0xf0, 0x0d, 0x74, 0xc7, 0xa8, + 0x47, 0xf8, 0x3d, 0x5b, 0x94, 0x76, 0xdf, 0xae, 0x26, 0x6f, 0xe1, 0x64, 0xcb, 0x9e, 0x6d, 0xad, + 0x9c, 0xcd, 0x56, 0x1f, 0xa1, 0x33, 0x46, 0x1d, 0x2f, 0xe6, 0x11, 0x57, 0x3a, 0xe3, 0x57, 0xb8, + 0xeb, 0x34, 0x9b, 0x2c, 0xa7, 0x5e, 0x58, 0xb1, 0xde, 0xc1, 0xf1, 0x5f, 0x2c, 0x13, 0xe0, 0x39, + 0x78, 0x85, 0x15, 0xeb, 0x08, 0x6e, 0xb2, 0x16, 0xc2, 0x1b, 0xe8, 0xb0, 0x07, 0x0a, 0xd1, 0xec, + 0xe4, 0xfe, 0xd9, 0xe9, 0x04, 0x8e, 0xd9, 0xf6, 0x88, 0xe1, 0x7b, 0x20, 0x4c, 0x67, 0xd2, 0xdc, + 0x81, 0x6d, 0x01, 0x9c, 0xfb, 0x02, 0x34, 0x26, 0x7a, 0x04, 0x41, 0x83, 0x63, 0xf0, 0x14, 0xda, + 0x4c, 0x8b, 0xea, 0x7e, 0xfa, 0xbf, 0xcd, 0xf8, 0xf0, 0x2e, 0xe5, 0x1a, 0x63, 0xe0, 0xdf, 0xea, + 0xfb, 0xf8, 0x41, 0x28, 0xcd, 0xb3, 0xf9, 0xff, 0xd3, 0xc9, 0x29, 0x1c, 0xd8, 0x59, 0x75, 0xdd, + 0x7a, 0x69, 0x55, 0x87, 0xaf, 0xeb, 0x5b, 0xbc, 0xee, 0x61, 0xbe, 0xec, 0x29, 0x1c, 0xdc, 0x18, + 0xcd, 0x8c, 0x68, 0x55, 0x9f, 0x79, 0x5f, 0xf7, 0xcd, 0x5f, 0xe2, 0x77, 0x00, 0x00, 0x00, 0xff, + 0xff, 0x6e, 0xbc, 0xe0, 0x61, 0x5c, 0x04, 0x00, 0x00, +} diff --git a/vendor/google.golang.org/appengine/internal/modules/modules_service.proto b/vendor/google.golang.org/appengine/internal/modules/modules_service.proto new file mode 100644 index 00000000..d29f0065 --- /dev/null +++ b/vendor/google.golang.org/appengine/internal/modules/modules_service.proto @@ -0,0 +1,80 @@ +syntax = "proto2"; +option go_package = "modules"; + +package appengine; + +message ModulesServiceError { + enum ErrorCode { + OK = 0; + INVALID_MODULE = 1; + INVALID_VERSION = 2; + INVALID_INSTANCES = 3; + TRANSIENT_ERROR = 4; + UNEXPECTED_STATE = 5; + } +} + +message GetModulesRequest { +} + +message GetModulesResponse { + repeated string module = 1; +} + +message GetVersionsRequest { + optional string module = 1; +} + +message GetVersionsResponse { + repeated string version = 1; +} + +message GetDefaultVersionRequest { + optional string module = 1; +} + +message GetDefaultVersionResponse { + required string version = 1; +} + +message GetNumInstancesRequest { + optional string module = 1; + optional string version = 2; +} + +message GetNumInstancesResponse { + required int64 instances = 1; +} + +message SetNumInstancesRequest { + optional string module = 1; + optional string version = 2; + required int64 instances = 3; +} + +message SetNumInstancesResponse {} + +message StartModuleRequest { + required string module = 1; + required string version = 2; +} + +message StartModuleResponse {} + +message StopModuleRequest { + optional string module = 1; + optional string version = 2; +} + +message StopModuleResponse {} + +message GetHostnameRequest { + optional string module = 1; + optional string version = 2; + optional string instance = 3; +} + +message GetHostnameResponse { + required string hostname = 1; +} + diff --git a/vendor/google.golang.org/appengine/namespace.go b/vendor/google.golang.org/appengine/namespace.go new file mode 100644 index 00000000..21860ca0 --- /dev/null +++ b/vendor/google.golang.org/appengine/namespace.go @@ -0,0 +1,25 @@ +// Copyright 2012 Google Inc. All rights reserved. +// Use of this source code is governed by the Apache 2.0 +// license that can be found in the LICENSE file. + +package appengine + +import ( + "fmt" + "regexp" + + "golang.org/x/net/context" + + "google.golang.org/appengine/internal" +) + +// Namespace returns a replacement context that operates within the given namespace. +func Namespace(c context.Context, namespace string) (context.Context, error) { + if !validNamespace.MatchString(namespace) { + return nil, fmt.Errorf("appengine: namespace %q does not match /%s/", namespace, validNamespace) + } + return internal.NamespacedContext(c, namespace), nil +} + +// validNamespace matches valid namespace names. +var validNamespace = regexp.MustCompile(`^[0-9A-Za-z._-]{0,100}$`) diff --git a/vendor/google.golang.org/appengine/timeout.go b/vendor/google.golang.org/appengine/timeout.go new file mode 100644 index 00000000..05642a99 --- /dev/null +++ b/vendor/google.golang.org/appengine/timeout.go @@ -0,0 +1,20 @@ +// Copyright 2013 Google Inc. All rights reserved. +// Use of this source code is governed by the Apache 2.0 +// license that can be found in the LICENSE file. + +package appengine + +import "golang.org/x/net/context" + +// IsTimeoutError reports whether err is a timeout error. +func IsTimeoutError(err error) bool { + if err == context.DeadlineExceeded { + return true + } + if t, ok := err.(interface { + IsTimeout() bool + }); ok { + return t.IsTimeout() + } + return false +} diff --git a/vendor/google.golang.org/appengine/travis_install.sh b/vendor/google.golang.org/appengine/travis_install.sh new file mode 100644 index 00000000..785b62f4 --- /dev/null +++ b/vendor/google.golang.org/appengine/travis_install.sh @@ -0,0 +1,18 @@ +#!/bin/bash +set -e + +if [[ $GO111MODULE == "on" ]]; then + go get . +else + go get -u -v $(go list -f '{{join .Imports "\n"}}{{"\n"}}{{join .TestImports "\n"}}' ./... | sort | uniq | grep -v appengine) +fi + +if [[ $GOAPP == "true" ]]; then + mkdir /tmp/sdk + curl -o /tmp/sdk.zip "https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip" + unzip -q /tmp/sdk.zip -d /tmp/sdk + # NOTE: Set the following env vars in the test script: + # export PATH="$PATH:/tmp/sdk/go_appengine" + # export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py +fi + diff --git a/vendor/google.golang.org/appengine/travis_test.sh b/vendor/google.golang.org/appengine/travis_test.sh new file mode 100644 index 00000000..d4390f04 --- /dev/null +++ b/vendor/google.golang.org/appengine/travis_test.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e + +go version +go test -v google.golang.org/appengine/... +go test -v -race google.golang.org/appengine/... +if [[ $GOAPP == "true" ]]; then + export PATH="$PATH:/tmp/sdk/go_appengine" + export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py + goapp version + goapp test -v google.golang.org/appengine/... +fi diff --git a/vendor/modules.txt b/vendor/modules.txt index ac9f5b3b..ff52620c 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,3 +1,5 @@ +# cloud.google.com/go v0.38.0 +cloud.google.com/go/compute/metadata # github.com/beevik/etree v1.1.0 github.com/beevik/etree # github.com/beorn7/perks v1.0.0 @@ -38,6 +40,8 @@ github.com/golang/protobuf/protoc-gen-go/plugin github.com/golang/protobuf/ptypes/any github.com/golang/protobuf/ptypes/duration github.com/golang/protobuf/ptypes/timestamp +# github.com/googleapis/gax-go/v2 v2.0.5 +github.com/googleapis/gax-go/v2 # github.com/gorilla/handlers v1.4.2 github.com/gorilla/handlers # github.com/gorilla/mux v1.7.3 @@ -46,6 +50,8 @@ github.com/gorilla/mux github.com/grpc-ecosystem/go-grpc-prometheus # github.com/gtank/cryptopasta v0.0.0-20170601214702-1f550f6f2f69 github.com/gtank/cryptopasta +# github.com/hashicorp/golang-lru v0.5.1 +github.com/hashicorp/golang-lru/simplelru # github.com/inconshreveable/mousetrap v1.0.0 github.com/inconshreveable/mousetrap # github.com/jonboulle/clockwork v0.1.0 @@ -93,6 +99,23 @@ github.com/spf13/cobra github.com/spf13/pflag # github.com/stretchr/testify v1.3.0 github.com/stretchr/testify/assert +# go.opencensus.io v0.21.0 +go.opencensus.io/plugin/ochttp +go.opencensus.io/plugin/ochttp/propagation/b3 +go.opencensus.io/stats +go.opencensus.io/stats/view +go.opencensus.io/tag +go.opencensus.io/trace +go.opencensus.io/trace/propagation +go.opencensus.io/metric/metricdata +go.opencensus.io/stats/internal +go.opencensus.io/internal/tagencoding +go.opencensus.io/metric/metricproducer +go.opencensus.io/internal +go.opencensus.io/trace/internal +go.opencensus.io/trace/tracestate +go.opencensus.io/resource +go.opencensus.io # golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 golang.org/x/crypto/bcrypt golang.org/x/crypto/blowfish @@ -103,9 +126,9 @@ golang.org/x/crypto/ed25519/internal/edwards25519 golang.org/x/lint/golint golang.org/x/lint # golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7 -golang.org/x/net/context golang.org/x/net/http2 golang.org/x/net/trace +golang.org/x/net/context golang.org/x/net/http/httpguts golang.org/x/net/http2/hpack golang.org/x/net/idna @@ -115,7 +138,10 @@ golang.org/x/net/context/ctxhttp golang.org/x/oauth2 golang.org/x/oauth2/bitbucket golang.org/x/oauth2/github +golang.org/x/oauth2/google golang.org/x/oauth2/internal +golang.org/x/oauth2/jws +golang.org/x/oauth2/jwt # golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a golang.org/x/sys/windows golang.org/x/sys/unix @@ -128,10 +154,23 @@ golang.org/x/text/transform golang.org/x/tools/go/ast/astutil golang.org/x/tools/go/gcexportdata golang.org/x/tools/go/internal/gcimporter +# google.golang.org/api v0.10.0 +google.golang.org/api/admin/directory/v1 +google.golang.org/api/gensupport +google.golang.org/api/googleapi +google.golang.org/api/option +google.golang.org/api/transport/http +google.golang.org/api/googleapi/internal/uritemplates +google.golang.org/api/internal +google.golang.org/api/googleapi/transport +google.golang.org/api/transport/http/internal/propagation # google.golang.org/appengine v1.6.1 +google.golang.org/appengine google.golang.org/appengine/cloudsql google.golang.org/appengine/urlfetch google.golang.org/appengine/internal +google.golang.org/appengine/internal/app_identity +google.golang.org/appengine/internal/modules google.golang.org/appengine/internal/urlfetch google.golang.org/appengine/internal/base google.golang.org/appengine/internal/datastore From 554870cea0afabb64c295ab4bac57b45fee7103d Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Mon, 28 Jan 2019 11:54:10 +0000 Subject: [PATCH 49/72] Add todo for configurable groups key --- connector/google/google.go | 1 + 1 file changed, 1 insertion(+) diff --git a/connector/google/google.go b/connector/google/google.go index ec2a6189..75f3d510 100644 --- a/connector/google/google.go +++ b/connector/google/google.go @@ -231,6 +231,7 @@ func (c *googleConnector) getGroups(email string) ([]string, error) { var userGroups []string for _, group := range groupsList.Groups { + // TODO (joelspeed): Make desried group key configurable userGroups = append(userGroups, group.Email) } From 658a2cc4777df8625c1cdf611b08b84b637bf6af Mon Sep 17 00:00:00 2001 From: Joel Speed Date: Mon, 28 Jan 2019 13:09:23 +0000 Subject: [PATCH 50/72] Make directory service during init --- connector/google/google.go | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/connector/google/google.go b/connector/google/google.go index 75f3d510..d86abbcb 100644 --- a/connector/google/google.go +++ b/connector/google/google.go @@ -62,6 +62,12 @@ func (c *Config) Open(id string, logger log.Logger) (conn connector.Connector, e scopes = append(scopes, "profile", "email") } + srv, err := createDirectoryService(c.ServiceAccountFilePath, c.AdminEmail) + if err != nil { + cancel() + return nil, fmt.Errorf("could not create directory service: %v", err) + } + clientID := c.ClientID return &googleConnector{ redirectURI: c.RedirectURI, @@ -80,6 +86,7 @@ func (c *Config) Open(id string, logger log.Logger) (conn connector.Connector, e hostedDomains: c.HostedDomains, serviceAccountFilePath: c.ServiceAccountFilePath, adminEmail: c.AdminEmail, + adminSrv: srv, }, nil } @@ -98,6 +105,7 @@ type googleConnector struct { hostedDomains []string serviceAccountFilePath string adminEmail string + adminSrv *admin.Service } func (c *googleConnector) Close() error { @@ -219,12 +227,7 @@ func (c *googleConnector) createIdentity(ctx context.Context, identity connector // getGroups creates a connection to the admin directory service and lists // all groups the user is a member of func (c *googleConnector) getGroups(email string) ([]string, error) { - srv, err := createDirectoryService(c.serviceAccountFilePath, c.adminEmail) - if err != nil { - return nil, fmt.Errorf("could not create directory service: %v", err) - } - - groupsList, err := srv.Groups.List().UserKey(email).Do() + groupsList, err := c.adminSrv.Groups.List().UserKey(email).Do() if err != nil { return nil, fmt.Errorf("could not list groups: %v", err) } From e11b2ceeee9063198ac2a02df7a6222c301d9b55 Mon Sep 17 00:00:00 2001 From: YanJin Date: Mon, 25 Nov 2019 12:15:07 +0100 Subject: [PATCH 51/72] add issuer in the templates.md --- Documentation/templates.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Documentation/templates.md b/Documentation/templates.md index 7906363b..043938d9 100644 --- a/Documentation/templates.md +++ b/Documentation/templates.md @@ -14,11 +14,13 @@ Steps: ```yaml frontend: dir: /path/to/custom/web + issuer: my-dex extra: tos_footer_link: "https://example.com/terms" client_logo_url: "../theme/client-logo.png" foo: "bar" ``` 5. Set the `frontend.dir` value to your own `web` directory. +6. Write the issuer in the `issuer` directory in order to modify the Dex title and the `Log in to <>` tag. To test your templates simply run Dex with a valid configuration and go through a login flow. \ No newline at end of file From a38e21589172ff6e6e5a042244ce38dc26ff3f93 Mon Sep 17 00:00:00 2001 From: Nandor Kracser Date: Tue, 3 Dec 2019 16:27:07 +0100 Subject: [PATCH 52/72] connector/google: support group whitelisting Signed-off-by: Nandor Kracser --- Documentation/connectors/google.md | 7 +++++++ connector/google/google.go | 16 +++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/Documentation/connectors/google.md b/Documentation/connectors/google.md index 1bfe321c..75224873 100644 --- a/Documentation/connectors/google.md +++ b/Documentation/connectors/google.md @@ -29,6 +29,13 @@ connectors: # hostedDomains: # - example.com + # The Google connector supports whitelisting allowed groups when using G Suite + # (Google Apps). The following field can be set to a list of groups + # that can log in: + # + # groups: + # - admins@example.com + # Google does not support the OpenID Connect groups claim and only supports # fetching a user's group membership with a service account. # This service account requires an authentication JSON file and the email diff --git a/connector/google/google.go b/connector/google/google.go index d86abbcb..84e5580d 100644 --- a/connector/google/google.go +++ b/connector/google/google.go @@ -13,9 +13,10 @@ import ( "golang.org/x/oauth2" "github.com/dexidp/dex/connector" + pkg_groups "github.com/dexidp/dex/pkg/groups" "github.com/dexidp/dex/pkg/log" "golang.org/x/oauth2/google" - "google.golang.org/api/admin/directory/v1" + admin "google.golang.org/api/admin/directory/v1" ) const ( @@ -34,6 +35,10 @@ type Config struct { // If this field is nonempty, only users from a listed domain will be allowed to log in HostedDomains []string `json:"hostedDomains"` + // Optional list of whitelisted groups + // If this field is nonempty, only users from a listed group will be allowed to log in + Groups []string `json:"groups"` + // Optional path to service account json // If nonempty, and groups claim is made, will use authentication from file to // check groups with the admin directory api @@ -84,6 +89,7 @@ func (c *Config) Open(id string, logger log.Logger) (conn connector.Connector, e logger: logger, cancel: cancel, hostedDomains: c.HostedDomains, + groups: c.Groups, serviceAccountFilePath: c.ServiceAccountFilePath, adminEmail: c.AdminEmail, adminSrv: srv, @@ -103,6 +109,7 @@ type googleConnector struct { cancel context.CancelFunc logger log.Logger hostedDomains []string + groups []string serviceAccountFilePath string adminEmail string adminSrv *admin.Service @@ -211,6 +218,13 @@ func (c *googleConnector) createIdentity(ctx context.Context, identity connector if err != nil { return identity, fmt.Errorf("google: could not retrieve groups: %v", err) } + + if len(c.groups) > 0 { + groups = pkg_groups.Filter(groups, c.groups) + if len(groups) == 0 { + return identity, fmt.Errorf("google: user %q is not in any of the required groups", claims.Username) + } + } } identity = connector.Identity{ From dbea20d0781443092f40aebbb765edc874c821f6 Mon Sep 17 00:00:00 2001 From: Nandor Kracser Date: Wed, 4 Dec 2019 10:46:53 +0100 Subject: [PATCH 53/72] update go to 1.13 and alpine to 3.10 Signed-off-by: Nandor Kracser --- .travis.yml | 2 +- Dockerfile | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 574298d7..d8ef066e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,7 +6,7 @@ dist: xenial matrix: include: - - go: '1.12.x' + - go: '1.13.x' env: global: diff --git a/Dockerfile b/Dockerfile index 9e10b5d1..d06b6cc8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,11 @@ -FROM golang:1.12.9-alpine +FROM golang:1.13-alpine RUN apk add --no-cache --update alpine-sdk COPY . /go/src/github.com/dexidp/dex RUN cd /go/src/github.com/dexidp/dex && make release-binary -FROM alpine:3.9 +FROM alpine:3.10 # Dex connectors, such as GitHub and Google logins require root certificates. # Proper installations should manage those certificates, but it's a bad user # experience when this doesn't work out of the box. From 4bb4d49952f936615be0ccdd1c1b9c5839b0535d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?N=C3=A1ndor=20Istv=C3=A1n=20Kr=C3=A1cser?= Date: Fri, 6 Dec 2019 08:46:32 +0100 Subject: [PATCH 54/72] add @sagikazarmark to MAINTAINERS --- MAINTAINERS | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index efcc71c0..fd526db6 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -1,4 +1,5 @@ Rithu John (@rithujohn191) Stephan Renatus (@srenatus) Joel Speed (@JoelSpeed) -Nandor Kracser (@bonifaido) +Nandor Kracser (@bonifaido) +Mark Sagi-Kazar (@sagikazarmark) From 9b5b604babb3ace45d3960d16b42c870c49ca8fa Mon Sep 17 00:00:00 2001 From: Nandor Kracser Date: Fri, 6 Dec 2019 09:24:16 +0100 Subject: [PATCH 55/72] go mod vendor with 1.13 Signed-off-by: Nandor Kracser --- go.mod | 2 + vendor/github.com/lib/pq/oid/gen.go | 93 -- vendor/golang.org/x/sys/unix/mkasm_darwin.go | 61 -- vendor/golang.org/x/sys/unix/mkpost.go | 122 --- vendor/golang.org/x/sys/unix/mksyscall.go | 407 -------- .../x/sys/unix/mksyscall_aix_ppc.go | 415 -------- .../x/sys/unix/mksyscall_aix_ppc64.go | 614 ----------- .../x/sys/unix/mksyscall_solaris.go | 335 ------ .../golang.org/x/sys/unix/mksysctl_openbsd.go | 355 ------- vendor/golang.org/x/sys/unix/mksysnum.go | 190 ---- vendor/golang.org/x/sys/unix/types_aix.go | 237 ----- vendor/golang.org/x/sys/unix/types_darwin.go | 283 ----- .../golang.org/x/sys/unix/types_dragonfly.go | 263 ----- vendor/golang.org/x/sys/unix/types_freebsd.go | 400 ------- vendor/golang.org/x/sys/unix/types_netbsd.go | 290 ------ vendor/golang.org/x/sys/unix/types_openbsd.go | 283 ----- vendor/golang.org/x/sys/unix/types_solaris.go | 266 ----- vendor/golang.org/x/text/unicode/bidi/gen.go | 133 --- .../x/text/unicode/bidi/gen_ranges.go | 57 - .../x/text/unicode/bidi/gen_trieval.go | 64 -- .../x/text/unicode/norm/maketables.go | 986 ------------------ .../golang.org/x/text/unicode/norm/triegen.go | 117 --- .../x/tools/go/gcexportdata/main.go | 99 -- vendor/modules.txt | 82 +- 24 files changed, 43 insertions(+), 6111 deletions(-) delete mode 100644 vendor/github.com/lib/pq/oid/gen.go delete mode 100644 vendor/golang.org/x/sys/unix/mkasm_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/mkpost.go delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall.go delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall_solaris.go delete mode 100644 vendor/golang.org/x/sys/unix/mksysctl_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/mksysnum.go delete mode 100644 vendor/golang.org/x/sys/unix/types_aix.go delete mode 100644 vendor/golang.org/x/sys/unix/types_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/types_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/types_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_solaris.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/gen.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/gen_ranges.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/gen_trieval.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/maketables.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/triegen.go delete mode 100644 vendor/golang.org/x/tools/go/gcexportdata/main.go diff --git a/go.mod b/go.mod index 78315f1b..739a38ef 100644 --- a/go.mod +++ b/go.mod @@ -60,3 +60,5 @@ require ( gopkg.in/ldap.v2 v2.5.1 gopkg.in/square/go-jose.v2 v2.3.1 ) + +go 1.13 diff --git a/vendor/github.com/lib/pq/oid/gen.go b/vendor/github.com/lib/pq/oid/gen.go deleted file mode 100644 index 7c634cdc..00000000 --- a/vendor/github.com/lib/pq/oid/gen.go +++ /dev/null @@ -1,93 +0,0 @@ -// +build ignore - -// Generate the table of OID values -// Run with 'go run gen.go'. -package main - -import ( - "database/sql" - "fmt" - "log" - "os" - "os/exec" - "strings" - - _ "github.com/lib/pq" -) - -// OID represent a postgres Object Identifier Type. -type OID struct { - ID int - Type string -} - -// Name returns an upper case version of the oid type. -func (o OID) Name() string { - return strings.ToUpper(o.Type) -} - -func main() { - datname := os.Getenv("PGDATABASE") - sslmode := os.Getenv("PGSSLMODE") - - if datname == "" { - os.Setenv("PGDATABASE", "pqgotest") - } - - if sslmode == "" { - os.Setenv("PGSSLMODE", "disable") - } - - db, err := sql.Open("postgres", "") - if err != nil { - log.Fatal(err) - } - rows, err := db.Query(` - SELECT typname, oid - FROM pg_type WHERE oid < 10000 - ORDER BY oid; - `) - if err != nil { - log.Fatal(err) - } - oids := make([]*OID, 0) - for rows.Next() { - var oid OID - if err = rows.Scan(&oid.Type, &oid.ID); err != nil { - log.Fatal(err) - } - oids = append(oids, &oid) - } - if err = rows.Err(); err != nil { - log.Fatal(err) - } - cmd := exec.Command("gofmt") - cmd.Stderr = os.Stderr - w, err := cmd.StdinPipe() - if err != nil { - log.Fatal(err) - } - f, err := os.Create("types.go") - if err != nil { - log.Fatal(err) - } - cmd.Stdout = f - err = cmd.Start() - if err != nil { - log.Fatal(err) - } - fmt.Fprintln(w, "// Code generated by gen.go. DO NOT EDIT.") - fmt.Fprintln(w, "\npackage oid") - fmt.Fprintln(w, "const (") - for _, oid := range oids { - fmt.Fprintf(w, "T_%s Oid = %d\n", oid.Type, oid.ID) - } - fmt.Fprintln(w, ")") - fmt.Fprintln(w, "var TypeName = map[Oid]string{") - for _, oid := range oids { - fmt.Fprintf(w, "T_%s: \"%s\",\n", oid.Type, oid.Name()) - } - fmt.Fprintln(w, "}") - w.Close() - cmd.Wait() -} diff --git a/vendor/golang.org/x/sys/unix/mkasm_darwin.go b/vendor/golang.org/x/sys/unix/mkasm_darwin.go deleted file mode 100644 index 4548b993..00000000 --- a/vendor/golang.org/x/sys/unix/mkasm_darwin.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// mkasm_darwin.go generates assembly trampolines to call libSystem routines from Go. -//This program must be run after mksyscall.go. -package main - -import ( - "bytes" - "fmt" - "io/ioutil" - "log" - "os" - "strings" -) - -func main() { - in1, err := ioutil.ReadFile("syscall_darwin.go") - if err != nil { - log.Fatalf("can't open syscall_darwin.go: %s", err) - } - arch := os.Args[1] - in2, err := ioutil.ReadFile(fmt.Sprintf("syscall_darwin_%s.go", arch)) - if err != nil { - log.Fatalf("can't open syscall_darwin_%s.go: %s", arch, err) - } - in3, err := ioutil.ReadFile(fmt.Sprintf("zsyscall_darwin_%s.go", arch)) - if err != nil { - log.Fatalf("can't open zsyscall_darwin_%s.go: %s", arch, err) - } - in := string(in1) + string(in2) + string(in3) - - trampolines := map[string]bool{} - - var out bytes.Buffer - - fmt.Fprintf(&out, "// go run mkasm_darwin.go %s\n", strings.Join(os.Args[1:], " ")) - fmt.Fprintf(&out, "// Code generated by the command above; DO NOT EDIT.\n") - fmt.Fprintf(&out, "\n") - fmt.Fprintf(&out, "// +build go1.12\n") - fmt.Fprintf(&out, "\n") - fmt.Fprintf(&out, "#include \"textflag.h\"\n") - for _, line := range strings.Split(in, "\n") { - if !strings.HasPrefix(line, "func ") || !strings.HasSuffix(line, "_trampoline()") { - continue - } - fn := line[5 : len(line)-13] - if !trampolines[fn] { - trampolines[fn] = true - fmt.Fprintf(&out, "TEXT ·%s_trampoline(SB),NOSPLIT,$0-0\n", fn) - fmt.Fprintf(&out, "\tJMP\t%s(SB)\n", fn) - } - } - err = ioutil.WriteFile(fmt.Sprintf("zsyscall_darwin_%s.s", arch), out.Bytes(), 0644) - if err != nil { - log.Fatalf("can't write zsyscall_darwin_%s.s: %s", arch, err) - } -} diff --git a/vendor/golang.org/x/sys/unix/mkpost.go b/vendor/golang.org/x/sys/unix/mkpost.go deleted file mode 100644 index eb433205..00000000 --- a/vendor/golang.org/x/sys/unix/mkpost.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// mkpost processes the output of cgo -godefs to -// modify the generated types. It is used to clean up -// the sys API in an architecture specific manner. -// -// mkpost is run after cgo -godefs; see README.md. -package main - -import ( - "bytes" - "fmt" - "go/format" - "io/ioutil" - "log" - "os" - "regexp" -) - -func main() { - // Get the OS and architecture (using GOARCH_TARGET if it exists) - goos := os.Getenv("GOOS") - goarch := os.Getenv("GOARCH_TARGET") - if goarch == "" { - goarch = os.Getenv("GOARCH") - } - // Check that we are using the Docker-based build system if we should be. - if goos == "linux" { - if os.Getenv("GOLANG_SYS_BUILD") != "docker" { - os.Stderr.WriteString("In the Docker-based build system, mkpost should not be called directly.\n") - os.Stderr.WriteString("See README.md\n") - os.Exit(1) - } - } - - b, err := ioutil.ReadAll(os.Stdin) - if err != nil { - log.Fatal(err) - } - - if goos == "aix" { - // Replace type of Atim, Mtim and Ctim by Timespec in Stat_t - // to avoid having both StTimespec and Timespec. - sttimespec := regexp.MustCompile(`_Ctype_struct_st_timespec`) - b = sttimespec.ReplaceAll(b, []byte("Timespec")) - } - - // Intentionally export __val fields in Fsid and Sigset_t - valRegex := regexp.MustCompile(`type (Fsid|Sigset_t) struct {(\s+)X__(bits|val)(\s+\S+\s+)}`) - b = valRegex.ReplaceAll(b, []byte("type $1 struct {${2}Val$4}")) - - // Intentionally export __fds_bits field in FdSet - fdSetRegex := regexp.MustCompile(`type (FdSet) struct {(\s+)X__fds_bits(\s+\S+\s+)}`) - b = fdSetRegex.ReplaceAll(b, []byte("type $1 struct {${2}Bits$3}")) - - // If we have empty Ptrace structs, we should delete them. Only s390x emits - // nonempty Ptrace structs. - ptraceRexexp := regexp.MustCompile(`type Ptrace((Psw|Fpregs|Per) struct {\s*})`) - b = ptraceRexexp.ReplaceAll(b, nil) - - // Replace the control_regs union with a blank identifier for now. - controlRegsRegex := regexp.MustCompile(`(Control_regs)\s+\[0\]uint64`) - b = controlRegsRegex.ReplaceAll(b, []byte("_ [0]uint64")) - - // Remove fields that are added by glibc - // Note that this is unstable as the identifers are private. - removeFieldsRegex := regexp.MustCompile(`X__glibc\S*`) - b = removeFieldsRegex.ReplaceAll(b, []byte("_")) - - // Convert [65]int8 to [65]byte in Utsname members to simplify - // conversion to string; see golang.org/issue/20753 - convertUtsnameRegex := regexp.MustCompile(`((Sys|Node|Domain)name|Release|Version|Machine)(\s+)\[(\d+)\]u?int8`) - b = convertUtsnameRegex.ReplaceAll(b, []byte("$1$3[$4]byte")) - - // Convert [1024]int8 to [1024]byte in Ptmget members - convertPtmget := regexp.MustCompile(`([SC]n)(\s+)\[(\d+)\]u?int8`) - b = convertPtmget.ReplaceAll(b, []byte("$1[$3]byte")) - - // Remove spare fields (e.g. in Statx_t) - spareFieldsRegex := regexp.MustCompile(`X__spare\S*`) - b = spareFieldsRegex.ReplaceAll(b, []byte("_")) - - // Remove cgo padding fields - removePaddingFieldsRegex := regexp.MustCompile(`Pad_cgo_\d+`) - b = removePaddingFieldsRegex.ReplaceAll(b, []byte("_")) - - // Remove padding, hidden, or unused fields - removeFieldsRegex = regexp.MustCompile(`\b(X_\S+|Padding)`) - b = removeFieldsRegex.ReplaceAll(b, []byte("_")) - - // Remove the first line of warning from cgo - b = b[bytes.IndexByte(b, '\n')+1:] - // Modify the command in the header to include: - // mkpost, our own warning, and a build tag. - replacement := fmt.Sprintf(`$1 | go run mkpost.go -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s,%s`, goarch, goos) - cgoCommandRegex := regexp.MustCompile(`(cgo -godefs .*)`) - b = cgoCommandRegex.ReplaceAll(b, []byte(replacement)) - - // Rename Stat_t time fields - if goos == "freebsd" && goarch == "386" { - // Hide Stat_t.[AMCB]tim_ext fields - renameStatTimeExtFieldsRegex := regexp.MustCompile(`[AMCB]tim_ext`) - b = renameStatTimeExtFieldsRegex.ReplaceAll(b, []byte("_")) - } - renameStatTimeFieldsRegex := regexp.MustCompile(`([AMCB])(?:irth)?time?(?:spec)?\s+(Timespec|StTimespec)`) - b = renameStatTimeFieldsRegex.ReplaceAll(b, []byte("${1}tim ${2}")) - - // gofmt - b, err = format.Source(b) - if err != nil { - log.Fatal(err) - } - - os.Stdout.Write(b) -} diff --git a/vendor/golang.org/x/sys/unix/mksyscall.go b/vendor/golang.org/x/sys/unix/mksyscall.go deleted file mode 100644 index e4af9424..00000000 --- a/vendor/golang.org/x/sys/unix/mksyscall.go +++ /dev/null @@ -1,407 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -This program reads a file containing function prototypes -(like syscall_darwin.go) and generates system call bodies. -The prototypes are marked by lines beginning with "//sys" -and read like func declarations if //sys is replaced by func, but: - * The parameter lists must give a name for each argument. - This includes return parameters. - * The parameter lists must give a type for each argument: - the (x, y, z int) shorthand is not allowed. - * If the return parameter is an error number, it must be named errno. - -A line beginning with //sysnb is like //sys, except that the -goroutine will not be suspended during the execution of the system -call. This must only be used for system calls which can never -block, as otherwise the system call could cause all goroutines to -hang. -*/ -package main - -import ( - "bufio" - "flag" - "fmt" - "os" - "regexp" - "strings" -) - -var ( - b32 = flag.Bool("b32", false, "32bit big-endian") - l32 = flag.Bool("l32", false, "32bit little-endian") - plan9 = flag.Bool("plan9", false, "plan9") - openbsd = flag.Bool("openbsd", false, "openbsd") - netbsd = flag.Bool("netbsd", false, "netbsd") - dragonfly = flag.Bool("dragonfly", false, "dragonfly") - arm = flag.Bool("arm", false, "arm") // 64-bit value should use (even, odd)-pair - tags = flag.String("tags", "", "build tags") - filename = flag.String("output", "", "output file name (standard output if omitted)") -) - -// cmdLine returns this programs's commandline arguments -func cmdLine() string { - return "go run mksyscall.go " + strings.Join(os.Args[1:], " ") -} - -// buildTags returns build tags -func buildTags() string { - return *tags -} - -// Param is function parameter -type Param struct { - Name string - Type string -} - -// usage prints the program usage -func usage() { - fmt.Fprintf(os.Stderr, "usage: go run mksyscall.go [-b32 | -l32] [-tags x,y] [file ...]\n") - os.Exit(1) -} - -// parseParamList parses parameter list and returns a slice of parameters -func parseParamList(list string) []string { - list = strings.TrimSpace(list) - if list == "" { - return []string{} - } - return regexp.MustCompile(`\s*,\s*`).Split(list, -1) -} - -// parseParam splits a parameter into name and type -func parseParam(p string) Param { - ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p) - if ps == nil { - fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p) - os.Exit(1) - } - return Param{ps[1], ps[2]} -} - -func main() { - // Get the OS and architecture (using GOARCH_TARGET if it exists) - goos := os.Getenv("GOOS") - if goos == "" { - fmt.Fprintln(os.Stderr, "GOOS not defined in environment") - os.Exit(1) - } - goarch := os.Getenv("GOARCH_TARGET") - if goarch == "" { - goarch = os.Getenv("GOARCH") - } - - // Check that we are using the Docker-based build system if we should - if goos == "linux" { - if os.Getenv("GOLANG_SYS_BUILD") != "docker" { - fmt.Fprintf(os.Stderr, "In the Docker-based build system, mksyscall should not be called directly.\n") - fmt.Fprintf(os.Stderr, "See README.md\n") - os.Exit(1) - } - } - - flag.Usage = usage - flag.Parse() - if len(flag.Args()) <= 0 { - fmt.Fprintf(os.Stderr, "no files to parse provided\n") - usage() - } - - endianness := "" - if *b32 { - endianness = "big-endian" - } else if *l32 { - endianness = "little-endian" - } - - libc := false - if goos == "darwin" && strings.Contains(buildTags(), ",go1.12") { - libc = true - } - trampolines := map[string]bool{} - - text := "" - for _, path := range flag.Args() { - file, err := os.Open(path) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - s := bufio.NewScanner(file) - for s.Scan() { - t := s.Text() - t = strings.TrimSpace(t) - t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `) - nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t) - if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil { - continue - } - - // Line must be of the form - // func Open(path string, mode int, perm int) (fd int, errno error) - // Split into name, in params, out params. - f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*((?i)SYS_[A-Z0-9_]+))?$`).FindStringSubmatch(t) - if f == nil { - fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t) - os.Exit(1) - } - funct, inps, outps, sysname := f[2], f[3], f[4], f[5] - - // ClockGettime doesn't have a syscall number on Darwin, only generate libc wrappers. - if goos == "darwin" && !libc && funct == "ClockGettime" { - continue - } - - // Split argument lists on comma. - in := parseParamList(inps) - out := parseParamList(outps) - - // Try in vain to keep people from editing this file. - // The theory is that they jump into the middle of the file - // without reading the header. - text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n" - - // Go function header. - outDecl := "" - if len(out) > 0 { - outDecl = fmt.Sprintf(" (%s)", strings.Join(out, ", ")) - } - text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outDecl) - - // Check if err return available - errvar := "" - for _, param := range out { - p := parseParam(param) - if p.Type == "error" { - errvar = p.Name - break - } - } - - // Prepare arguments to Syscall. - var args []string - n := 0 - for _, param := range in { - p := parseParam(param) - if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil { - args = append(args, "uintptr(unsafe.Pointer("+p.Name+"))") - } else if p.Type == "string" && errvar != "" { - text += fmt.Sprintf("\tvar _p%d *byte\n", n) - text += fmt.Sprintf("\t_p%d, %s = BytePtrFromString(%s)\n", n, errvar, p.Name) - text += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar) - args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) - n++ - } else if p.Type == "string" { - fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n") - text += fmt.Sprintf("\tvar _p%d *byte\n", n) - text += fmt.Sprintf("\t_p%d, _ = BytePtrFromString(%s)\n", n, p.Name) - args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) - n++ - } else if regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type) != nil { - // Convert slice into pointer, length. - // Have to be careful not to take address of &a[0] if len == 0: - // pass dummy pointer in that case. - // Used to pass nil, but some OSes or simulators reject write(fd, nil, 0). - text += fmt.Sprintf("\tvar _p%d unsafe.Pointer\n", n) - text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = unsafe.Pointer(&%s[0])\n\t}", p.Name, n, p.Name) - text += fmt.Sprintf(" else {\n\t\t_p%d = unsafe.Pointer(&_zero)\n\t}\n", n) - args = append(args, fmt.Sprintf("uintptr(_p%d)", n), fmt.Sprintf("uintptr(len(%s))", p.Name)) - n++ - } else if p.Type == "int64" && (*openbsd || *netbsd) { - args = append(args, "0") - if endianness == "big-endian" { - args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name)) - } else if endianness == "little-endian" { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name)) - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name)) - } - } else if p.Type == "int64" && *dragonfly { - if regexp.MustCompile(`^(?i)extp(read|write)`).FindStringSubmatch(funct) == nil { - args = append(args, "0") - } - if endianness == "big-endian" { - args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name)) - } else if endianness == "little-endian" { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name)) - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name)) - } - } else if (p.Type == "int64" || p.Type == "uint64") && endianness != "" { - if len(args)%2 == 1 && *arm { - // arm abi specifies 64-bit argument uses - // (even, odd) pair - args = append(args, "0") - } - if endianness == "big-endian" { - args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name)) - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name)) - } - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name)) - } - } - - // Determine which form to use; pad args with zeros. - asm := "Syscall" - if nonblock != nil { - if errvar == "" && goos == "linux" { - asm = "RawSyscallNoError" - } else { - asm = "RawSyscall" - } - } else { - if errvar == "" && goos == "linux" { - asm = "SyscallNoError" - } - } - if len(args) <= 3 { - for len(args) < 3 { - args = append(args, "0") - } - } else if len(args) <= 6 { - asm += "6" - for len(args) < 6 { - args = append(args, "0") - } - } else if len(args) <= 9 { - asm += "9" - for len(args) < 9 { - args = append(args, "0") - } - } else { - fmt.Fprintf(os.Stderr, "%s:%s too many arguments to system call\n", path, funct) - } - - // System call number. - if sysname == "" { - sysname = "SYS_" + funct - sysname = regexp.MustCompile(`([a-z])([A-Z])`).ReplaceAllString(sysname, `${1}_$2`) - sysname = strings.ToUpper(sysname) - } - - var libcFn string - if libc { - asm = "syscall_" + strings.ToLower(asm[:1]) + asm[1:] // internal syscall call - sysname = strings.TrimPrefix(sysname, "SYS_") // remove SYS_ - sysname = strings.ToLower(sysname) // lowercase - if sysname == "getdirentries64" { - // Special case - libSystem name and - // raw syscall name don't match. - sysname = "__getdirentries64" - } - libcFn = sysname - sysname = "funcPC(libc_" + sysname + "_trampoline)" - } - - // Actual call. - arglist := strings.Join(args, ", ") - call := fmt.Sprintf("%s(%s, %s)", asm, sysname, arglist) - - // Assign return values. - body := "" - ret := []string{"_", "_", "_"} - doErrno := false - for i := 0; i < len(out); i++ { - p := parseParam(out[i]) - reg := "" - if p.Name == "err" && !*plan9 { - reg = "e1" - ret[2] = reg - doErrno = true - } else if p.Name == "err" && *plan9 { - ret[0] = "r0" - ret[2] = "e1" - break - } else { - reg = fmt.Sprintf("r%d", i) - ret[i] = reg - } - if p.Type == "bool" { - reg = fmt.Sprintf("%s != 0", reg) - } - if p.Type == "int64" && endianness != "" { - // 64-bit number in r1:r0 or r0:r1. - if i+2 > len(out) { - fmt.Fprintf(os.Stderr, "%s:%s not enough registers for int64 return\n", path, funct) - } - if endianness == "big-endian" { - reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i, i+1) - } else { - reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i+1, i) - } - ret[i] = fmt.Sprintf("r%d", i) - ret[i+1] = fmt.Sprintf("r%d", i+1) - } - if reg != "e1" || *plan9 { - body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg) - } - } - if ret[0] == "_" && ret[1] == "_" && ret[2] == "_" { - text += fmt.Sprintf("\t%s\n", call) - } else { - if errvar == "" && goos == "linux" { - // raw syscall without error on Linux, see golang.org/issue/22924 - text += fmt.Sprintf("\t%s, %s := %s\n", ret[0], ret[1], call) - } else { - text += fmt.Sprintf("\t%s, %s, %s := %s\n", ret[0], ret[1], ret[2], call) - } - } - text += body - - if *plan9 && ret[2] == "e1" { - text += "\tif int32(r0) == -1 {\n" - text += "\t\terr = e1\n" - text += "\t}\n" - } else if doErrno { - text += "\tif e1 != 0 {\n" - text += "\t\terr = errnoErr(e1)\n" - text += "\t}\n" - } - text += "\treturn\n" - text += "}\n\n" - - if libc && !trampolines[libcFn] { - // some system calls share a trampoline, like read and readlen. - trampolines[libcFn] = true - // Declare assembly trampoline. - text += fmt.Sprintf("func libc_%s_trampoline()\n", libcFn) - // Assembly trampoline calls the libc_* function, which this magic - // redirects to use the function from libSystem. - text += fmt.Sprintf("//go:linkname libc_%s libc_%s\n", libcFn, libcFn) - text += fmt.Sprintf("//go:cgo_import_dynamic libc_%s %s \"/usr/lib/libSystem.B.dylib\"\n", libcFn, libcFn) - text += "\n" - } - } - if err := s.Err(); err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - file.Close() - } - fmt.Printf(srcTemplate, cmdLine(), buildTags(), text) -} - -const srcTemplate = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -%s -` diff --git a/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.go b/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.go deleted file mode 100644 index 3be3cdfc..00000000 --- a/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.go +++ /dev/null @@ -1,415 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -This program reads a file containing function prototypes -(like syscall_aix.go) and generates system call bodies. -The prototypes are marked by lines beginning with "//sys" -and read like func declarations if //sys is replaced by func, but: - * The parameter lists must give a name for each argument. - This includes return parameters. - * The parameter lists must give a type for each argument: - the (x, y, z int) shorthand is not allowed. - * If the return parameter is an error number, it must be named err. - * If go func name needs to be different than its libc name, - * or the function is not in libc, name could be specified - * at the end, after "=" sign, like - //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt -*/ -package main - -import ( - "bufio" - "flag" - "fmt" - "os" - "regexp" - "strings" -) - -var ( - b32 = flag.Bool("b32", false, "32bit big-endian") - l32 = flag.Bool("l32", false, "32bit little-endian") - aix = flag.Bool("aix", false, "aix") - tags = flag.String("tags", "", "build tags") -) - -// cmdLine returns this programs's commandline arguments -func cmdLine() string { - return "go run mksyscall_aix_ppc.go " + strings.Join(os.Args[1:], " ") -} - -// buildTags returns build tags -func buildTags() string { - return *tags -} - -// Param is function parameter -type Param struct { - Name string - Type string -} - -// usage prints the program usage -func usage() { - fmt.Fprintf(os.Stderr, "usage: go run mksyscall_aix_ppc.go [-b32 | -l32] [-tags x,y] [file ...]\n") - os.Exit(1) -} - -// parseParamList parses parameter list and returns a slice of parameters -func parseParamList(list string) []string { - list = strings.TrimSpace(list) - if list == "" { - return []string{} - } - return regexp.MustCompile(`\s*,\s*`).Split(list, -1) -} - -// parseParam splits a parameter into name and type -func parseParam(p string) Param { - ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p) - if ps == nil { - fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p) - os.Exit(1) - } - return Param{ps[1], ps[2]} -} - -func main() { - flag.Usage = usage - flag.Parse() - if len(flag.Args()) <= 0 { - fmt.Fprintf(os.Stderr, "no files to parse provided\n") - usage() - } - - endianness := "" - if *b32 { - endianness = "big-endian" - } else if *l32 { - endianness = "little-endian" - } - - pack := "" - text := "" - cExtern := "/*\n#include \n#include \n" - for _, path := range flag.Args() { - file, err := os.Open(path) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - s := bufio.NewScanner(file) - for s.Scan() { - t := s.Text() - t = strings.TrimSpace(t) - t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `) - if p := regexp.MustCompile(`^package (\S+)$`).FindStringSubmatch(t); p != nil && pack == "" { - pack = p[1] - } - nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t) - if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil { - continue - } - - // Line must be of the form - // func Open(path string, mode int, perm int) (fd int, err error) - // Split into name, in params, out params. - f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$`).FindStringSubmatch(t) - if f == nil { - fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t) - os.Exit(1) - } - funct, inps, outps, modname, sysname := f[2], f[3], f[4], f[5], f[6] - - // Split argument lists on comma. - in := parseParamList(inps) - out := parseParamList(outps) - - inps = strings.Join(in, ", ") - outps = strings.Join(out, ", ") - - // Try in vain to keep people from editing this file. - // The theory is that they jump into the middle of the file - // without reading the header. - text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n" - - // Check if value return, err return available - errvar := "" - retvar := "" - rettype := "" - for _, param := range out { - p := parseParam(param) - if p.Type == "error" { - errvar = p.Name - } else { - retvar = p.Name - rettype = p.Type - } - } - - // System call name. - if sysname == "" { - sysname = funct - } - sysname = regexp.MustCompile(`([a-z])([A-Z])`).ReplaceAllString(sysname, `${1}_$2`) - sysname = strings.ToLower(sysname) // All libc functions are lowercase. - - cRettype := "" - if rettype == "unsafe.Pointer" { - cRettype = "uintptr_t" - } else if rettype == "uintptr" { - cRettype = "uintptr_t" - } else if regexp.MustCompile(`^_`).FindStringSubmatch(rettype) != nil { - cRettype = "uintptr_t" - } else if rettype == "int" { - cRettype = "int" - } else if rettype == "int32" { - cRettype = "int" - } else if rettype == "int64" { - cRettype = "long long" - } else if rettype == "uint32" { - cRettype = "unsigned int" - } else if rettype == "uint64" { - cRettype = "unsigned long long" - } else { - cRettype = "int" - } - if sysname == "exit" { - cRettype = "void" - } - - // Change p.Types to c - var cIn []string - for _, param := range in { - p := parseParam(param) - if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil { - cIn = append(cIn, "uintptr_t") - } else if p.Type == "string" { - cIn = append(cIn, "uintptr_t") - } else if regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type) != nil { - cIn = append(cIn, "uintptr_t", "size_t") - } else if p.Type == "unsafe.Pointer" { - cIn = append(cIn, "uintptr_t") - } else if p.Type == "uintptr" { - cIn = append(cIn, "uintptr_t") - } else if regexp.MustCompile(`^_`).FindStringSubmatch(p.Type) != nil { - cIn = append(cIn, "uintptr_t") - } else if p.Type == "int" { - cIn = append(cIn, "int") - } else if p.Type == "int32" { - cIn = append(cIn, "int") - } else if p.Type == "int64" { - cIn = append(cIn, "long long") - } else if p.Type == "uint32" { - cIn = append(cIn, "unsigned int") - } else if p.Type == "uint64" { - cIn = append(cIn, "unsigned long long") - } else { - cIn = append(cIn, "int") - } - } - - if funct != "fcntl" && funct != "FcntlInt" && funct != "readlen" && funct != "writelen" { - if sysname == "select" { - // select is a keyword of Go. Its name is - // changed to c_select. - cExtern += "#define c_select select\n" - } - // Imports of system calls from libc - cExtern += fmt.Sprintf("%s %s", cRettype, sysname) - cIn := strings.Join(cIn, ", ") - cExtern += fmt.Sprintf("(%s);\n", cIn) - } - - // So file name. - if *aix { - if modname == "" { - modname = "libc.a/shr_64.o" - } else { - fmt.Fprintf(os.Stderr, "%s: only syscall using libc are available\n", funct) - os.Exit(1) - } - } - - strconvfunc := "C.CString" - - // Go function header. - if outps != "" { - outps = fmt.Sprintf(" (%s)", outps) - } - if text != "" { - text += "\n" - } - - text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outps) - - // Prepare arguments to Syscall. - var args []string - n := 0 - argN := 0 - for _, param := range in { - p := parseParam(param) - if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil { - args = append(args, "C.uintptr_t(uintptr(unsafe.Pointer("+p.Name+")))") - } else if p.Type == "string" && errvar != "" { - text += fmt.Sprintf("\t_p%d := uintptr(unsafe.Pointer(%s(%s)))\n", n, strconvfunc, p.Name) - args = append(args, fmt.Sprintf("C.uintptr_t(_p%d)", n)) - n++ - } else if p.Type == "string" { - fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n") - text += fmt.Sprintf("\t_p%d := uintptr(unsafe.Pointer(%s(%s)))\n", n, strconvfunc, p.Name) - args = append(args, fmt.Sprintf("C.uintptr_t(_p%d)", n)) - n++ - } else if m := regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type); m != nil { - // Convert slice into pointer, length. - // Have to be careful not to take address of &a[0] if len == 0: - // pass nil in that case. - text += fmt.Sprintf("\tvar _p%d *%s\n", n, m[1]) - text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = &%s[0]\n\t}\n", p.Name, n, p.Name) - args = append(args, fmt.Sprintf("C.uintptr_t(uintptr(unsafe.Pointer(_p%d)))", n)) - n++ - text += fmt.Sprintf("\tvar _p%d int\n", n) - text += fmt.Sprintf("\t_p%d = len(%s)\n", n, p.Name) - args = append(args, fmt.Sprintf("C.size_t(_p%d)", n)) - n++ - } else if p.Type == "int64" && endianness != "" { - if endianness == "big-endian" { - args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name)) - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name)) - } - n++ - } else if p.Type == "bool" { - text += fmt.Sprintf("\tvar _p%d uint32\n", n) - text += fmt.Sprintf("\tif %s {\n\t\t_p%d = 1\n\t} else {\n\t\t_p%d = 0\n\t}\n", p.Name, n, n) - args = append(args, fmt.Sprintf("_p%d", n)) - } else if regexp.MustCompile(`^_`).FindStringSubmatch(p.Type) != nil { - args = append(args, fmt.Sprintf("C.uintptr_t(uintptr(%s))", p.Name)) - } else if p.Type == "unsafe.Pointer" { - args = append(args, fmt.Sprintf("C.uintptr_t(uintptr(%s))", p.Name)) - } else if p.Type == "int" { - if (argN == 2) && ((funct == "readlen") || (funct == "writelen")) { - args = append(args, fmt.Sprintf("C.size_t(%s)", p.Name)) - } else if argN == 0 && funct == "fcntl" { - args = append(args, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - } else if (argN == 2) && ((funct == "fcntl") || (funct == "FcntlInt")) { - args = append(args, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - } else { - args = append(args, fmt.Sprintf("C.int(%s)", p.Name)) - } - } else if p.Type == "int32" { - args = append(args, fmt.Sprintf("C.int(%s)", p.Name)) - } else if p.Type == "int64" { - args = append(args, fmt.Sprintf("C.longlong(%s)", p.Name)) - } else if p.Type == "uint32" { - args = append(args, fmt.Sprintf("C.uint(%s)", p.Name)) - } else if p.Type == "uint64" { - args = append(args, fmt.Sprintf("C.ulonglong(%s)", p.Name)) - } else if p.Type == "uintptr" { - args = append(args, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - } else { - args = append(args, fmt.Sprintf("C.int(%s)", p.Name)) - } - argN++ - } - - // Actual call. - arglist := strings.Join(args, ", ") - call := "" - if sysname == "exit" { - if errvar != "" { - call += "er :=" - } else { - call += "" - } - } else if errvar != "" { - call += "r0,er :=" - } else if retvar != "" { - call += "r0,_ :=" - } else { - call += "" - } - if sysname == "select" { - // select is a keyword of Go. Its name is - // changed to c_select. - call += fmt.Sprintf("C.c_%s(%s)", sysname, arglist) - } else { - call += fmt.Sprintf("C.%s(%s)", sysname, arglist) - } - - // Assign return values. - body := "" - for i := 0; i < len(out); i++ { - p := parseParam(out[i]) - reg := "" - if p.Name == "err" { - reg = "e1" - } else { - reg = "r0" - } - if reg != "e1" { - body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg) - } - } - - // verify return - if sysname != "exit" && errvar != "" { - if regexp.MustCompile(`^uintptr`).FindStringSubmatch(cRettype) != nil { - body += "\tif (uintptr(r0) ==^uintptr(0) && er != nil) {\n" - body += fmt.Sprintf("\t\t%s = er\n", errvar) - body += "\t}\n" - } else { - body += "\tif (r0 ==-1 && er != nil) {\n" - body += fmt.Sprintf("\t\t%s = er\n", errvar) - body += "\t}\n" - } - } else if errvar != "" { - body += "\tif (er != nil) {\n" - body += fmt.Sprintf("\t\t%s = er\n", errvar) - body += "\t}\n" - } - - text += fmt.Sprintf("\t%s\n", call) - text += body - - text += "\treturn\n" - text += "}\n" - } - if err := s.Err(); err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - file.Close() - } - imp := "" - if pack != "unix" { - imp = "import \"golang.org/x/sys/unix\"\n" - - } - fmt.Printf(srcTemplate, cmdLine(), buildTags(), pack, cExtern, imp, text) -} - -const srcTemplate = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s - -package %s - - -%s -*/ -import "C" -import ( - "unsafe" -) - - -%s - -%s -` diff --git a/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.go b/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.go deleted file mode 100644 index c9600995..00000000 --- a/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.go +++ /dev/null @@ -1,614 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -This program reads a file containing function prototypes -(like syscall_aix.go) and generates system call bodies. -The prototypes are marked by lines beginning with "//sys" -and read like func declarations if //sys is replaced by func, but: - * The parameter lists must give a name for each argument. - This includes return parameters. - * The parameter lists must give a type for each argument: - the (x, y, z int) shorthand is not allowed. - * If the return parameter is an error number, it must be named err. - * If go func name needs to be different than its libc name, - * or the function is not in libc, name could be specified - * at the end, after "=" sign, like - //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt - - -This program will generate three files and handle both gc and gccgo implementation: - - zsyscall_aix_ppc64.go: the common part of each implementation (error handler, pointer creation) - - zsyscall_aix_ppc64_gc.go: gc part with //go_cgo_import_dynamic and a call to syscall6 - - zsyscall_aix_ppc64_gccgo.go: gccgo part with C function and conversion to C type. - - The generated code looks like this - -zsyscall_aix_ppc64.go -func asyscall(...) (n int, err error) { - // Pointer Creation - r1, e1 := callasyscall(...) - // Type Conversion - // Error Handler - return -} - -zsyscall_aix_ppc64_gc.go -//go:cgo_import_dynamic libc_asyscall asyscall "libc.a/shr_64.o" -//go:linkname libc_asyscall libc_asyscall -var asyscall syscallFunc - -func callasyscall(...) (r1 uintptr, e1 Errno) { - r1, _, e1 = syscall6(uintptr(unsafe.Pointer(&libc_asyscall)), "nb_args", ... ) - return -} - -zsyscall_aix_ppc64_ggcgo.go - -// int asyscall(...) - -import "C" - -func callasyscall(...) (r1 uintptr, e1 Errno) { - r1 = uintptr(C.asyscall(...)) - e1 = syscall.GetErrno() - return -} -*/ - -package main - -import ( - "bufio" - "flag" - "fmt" - "io/ioutil" - "os" - "regexp" - "strings" -) - -var ( - b32 = flag.Bool("b32", false, "32bit big-endian") - l32 = flag.Bool("l32", false, "32bit little-endian") - aix = flag.Bool("aix", false, "aix") - tags = flag.String("tags", "", "build tags") -) - -// cmdLine returns this programs's commandline arguments -func cmdLine() string { - return "go run mksyscall_aix_ppc64.go " + strings.Join(os.Args[1:], " ") -} - -// buildTags returns build tags -func buildTags() string { - return *tags -} - -// Param is function parameter -type Param struct { - Name string - Type string -} - -// usage prints the program usage -func usage() { - fmt.Fprintf(os.Stderr, "usage: go run mksyscall_aix_ppc64.go [-b32 | -l32] [-tags x,y] [file ...]\n") - os.Exit(1) -} - -// parseParamList parses parameter list and returns a slice of parameters -func parseParamList(list string) []string { - list = strings.TrimSpace(list) - if list == "" { - return []string{} - } - return regexp.MustCompile(`\s*,\s*`).Split(list, -1) -} - -// parseParam splits a parameter into name and type -func parseParam(p string) Param { - ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p) - if ps == nil { - fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p) - os.Exit(1) - } - return Param{ps[1], ps[2]} -} - -func main() { - flag.Usage = usage - flag.Parse() - if len(flag.Args()) <= 0 { - fmt.Fprintf(os.Stderr, "no files to parse provided\n") - usage() - } - - endianness := "" - if *b32 { - endianness = "big-endian" - } else if *l32 { - endianness = "little-endian" - } - - pack := "" - // GCCGO - textgccgo := "" - cExtern := "/*\n#include \n" - // GC - textgc := "" - dynimports := "" - linknames := "" - var vars []string - // COMMON - textcommon := "" - for _, path := range flag.Args() { - file, err := os.Open(path) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - s := bufio.NewScanner(file) - for s.Scan() { - t := s.Text() - t = strings.TrimSpace(t) - t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `) - if p := regexp.MustCompile(`^package (\S+)$`).FindStringSubmatch(t); p != nil && pack == "" { - pack = p[1] - } - nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t) - if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil { - continue - } - - // Line must be of the form - // func Open(path string, mode int, perm int) (fd int, err error) - // Split into name, in params, out params. - f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$`).FindStringSubmatch(t) - if f == nil { - fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t) - os.Exit(1) - } - funct, inps, outps, modname, sysname := f[2], f[3], f[4], f[5], f[6] - - // Split argument lists on comma. - in := parseParamList(inps) - out := parseParamList(outps) - - inps = strings.Join(in, ", ") - outps = strings.Join(out, ", ") - - if sysname == "" { - sysname = funct - } - - onlyCommon := false - if funct == "readlen" || funct == "writelen" || funct == "FcntlInt" || funct == "FcntlFlock" { - // This function call another syscall which is already implemented. - // Therefore, the gc and gccgo part must not be generated. - onlyCommon = true - } - - // Try in vain to keep people from editing this file. - // The theory is that they jump into the middle of the file - // without reading the header. - - textcommon += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n" - if !onlyCommon { - textgccgo += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n" - textgc += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n" - } - - // Check if value return, err return available - errvar := "" - rettype := "" - for _, param := range out { - p := parseParam(param) - if p.Type == "error" { - errvar = p.Name - } else { - rettype = p.Type - } - } - - sysname = regexp.MustCompile(`([a-z])([A-Z])`).ReplaceAllString(sysname, `${1}_$2`) - sysname = strings.ToLower(sysname) // All libc functions are lowercase. - - // GCCGO Prototype return type - cRettype := "" - if rettype == "unsafe.Pointer" { - cRettype = "uintptr_t" - } else if rettype == "uintptr" { - cRettype = "uintptr_t" - } else if regexp.MustCompile(`^_`).FindStringSubmatch(rettype) != nil { - cRettype = "uintptr_t" - } else if rettype == "int" { - cRettype = "int" - } else if rettype == "int32" { - cRettype = "int" - } else if rettype == "int64" { - cRettype = "long long" - } else if rettype == "uint32" { - cRettype = "unsigned int" - } else if rettype == "uint64" { - cRettype = "unsigned long long" - } else { - cRettype = "int" - } - if sysname == "exit" { - cRettype = "void" - } - - // GCCGO Prototype arguments type - var cIn []string - for i, param := range in { - p := parseParam(param) - if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil { - cIn = append(cIn, "uintptr_t") - } else if p.Type == "string" { - cIn = append(cIn, "uintptr_t") - } else if regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type) != nil { - cIn = append(cIn, "uintptr_t", "size_t") - } else if p.Type == "unsafe.Pointer" { - cIn = append(cIn, "uintptr_t") - } else if p.Type == "uintptr" { - cIn = append(cIn, "uintptr_t") - } else if regexp.MustCompile(`^_`).FindStringSubmatch(p.Type) != nil { - cIn = append(cIn, "uintptr_t") - } else if p.Type == "int" { - if (i == 0 || i == 2) && funct == "fcntl" { - // These fcntl arguments needs to be uintptr to be able to call FcntlInt and FcntlFlock - cIn = append(cIn, "uintptr_t") - } else { - cIn = append(cIn, "int") - } - - } else if p.Type == "int32" { - cIn = append(cIn, "int") - } else if p.Type == "int64" { - cIn = append(cIn, "long long") - } else if p.Type == "uint32" { - cIn = append(cIn, "unsigned int") - } else if p.Type == "uint64" { - cIn = append(cIn, "unsigned long long") - } else { - cIn = append(cIn, "int") - } - } - - if !onlyCommon { - // GCCGO Prototype Generation - // Imports of system calls from libc - if sysname == "select" { - // select is a keyword of Go. Its name is - // changed to c_select. - cExtern += "#define c_select select\n" - } - cExtern += fmt.Sprintf("%s %s", cRettype, sysname) - cIn := strings.Join(cIn, ", ") - cExtern += fmt.Sprintf("(%s);\n", cIn) - } - // GC Library name - if modname == "" { - modname = "libc.a/shr_64.o" - } else { - fmt.Fprintf(os.Stderr, "%s: only syscall using libc are available\n", funct) - os.Exit(1) - } - sysvarname := fmt.Sprintf("libc_%s", sysname) - - if !onlyCommon { - // GC Runtime import of function to allow cross-platform builds. - dynimports += fmt.Sprintf("//go:cgo_import_dynamic %s %s \"%s\"\n", sysvarname, sysname, modname) - // GC Link symbol to proc address variable. - linknames += fmt.Sprintf("//go:linkname %s %s\n", sysvarname, sysvarname) - // GC Library proc address variable. - vars = append(vars, sysvarname) - } - - strconvfunc := "BytePtrFromString" - strconvtype := "*byte" - - // Go function header. - if outps != "" { - outps = fmt.Sprintf(" (%s)", outps) - } - if textcommon != "" { - textcommon += "\n" - } - - textcommon += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outps) - - // Prepare arguments tocall. - var argscommon []string // Arguments in the common part - var argscall []string // Arguments for call prototype - var argsgc []string // Arguments for gc call (with syscall6) - var argsgccgo []string // Arguments for gccgo call (with C.name_of_syscall) - n := 0 - argN := 0 - for _, param := range in { - p := parseParam(param) - if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil { - argscommon = append(argscommon, fmt.Sprintf("uintptr(unsafe.Pointer(%s))", p.Name)) - argscall = append(argscall, fmt.Sprintf("%s uintptr", p.Name)) - argsgc = append(argsgc, p.Name) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - } else if p.Type == "string" && errvar != "" { - textcommon += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype) - textcommon += fmt.Sprintf("\t_p%d, %s = %s(%s)\n", n, errvar, strconvfunc, p.Name) - textcommon += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar) - - argscommon = append(argscommon, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) - argscall = append(argscall, fmt.Sprintf("_p%d uintptr ", n)) - argsgc = append(argsgc, fmt.Sprintf("_p%d", n)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(_p%d)", n)) - n++ - } else if p.Type == "string" { - fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n") - textcommon += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype) - textcommon += fmt.Sprintf("\t_p%d, %s = %s(%s)\n", n, errvar, strconvfunc, p.Name) - textcommon += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar) - - argscommon = append(argscommon, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) - argscall = append(argscall, fmt.Sprintf("_p%d uintptr", n)) - argsgc = append(argsgc, fmt.Sprintf("_p%d", n)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(_p%d)", n)) - n++ - } else if m := regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type); m != nil { - // Convert slice into pointer, length. - // Have to be careful not to take address of &a[0] if len == 0: - // pass nil in that case. - textcommon += fmt.Sprintf("\tvar _p%d *%s\n", n, m[1]) - textcommon += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = &%s[0]\n\t}\n", p.Name, n, p.Name) - argscommon = append(argscommon, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n), fmt.Sprintf("len(%s)", p.Name)) - argscall = append(argscall, fmt.Sprintf("_p%d uintptr", n), fmt.Sprintf("_lenp%d int", n)) - argsgc = append(argsgc, fmt.Sprintf("_p%d", n), fmt.Sprintf("uintptr(_lenp%d)", n)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(_p%d)", n), fmt.Sprintf("C.size_t(_lenp%d)", n)) - n++ - } else if p.Type == "int64" && endianness != "" { - fmt.Fprintf(os.Stderr, path+":"+funct+" uses int64 with 32 bits mode. Case not yet implemented\n") - } else if p.Type == "bool" { - fmt.Fprintf(os.Stderr, path+":"+funct+" uses bool. Case not yet implemented\n") - } else if regexp.MustCompile(`^_`).FindStringSubmatch(p.Type) != nil || p.Type == "unsafe.Pointer" { - argscommon = append(argscommon, fmt.Sprintf("uintptr(%s)", p.Name)) - argscall = append(argscall, fmt.Sprintf("%s uintptr", p.Name)) - argsgc = append(argsgc, p.Name) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - } else if p.Type == "int" { - if (argN == 0 || argN == 2) && ((funct == "fcntl") || (funct == "FcntlInt") || (funct == "FcntlFlock")) { - // These fcntl arguments need to be uintptr to be able to call FcntlInt and FcntlFlock - argscommon = append(argscommon, fmt.Sprintf("uintptr(%s)", p.Name)) - argscall = append(argscall, fmt.Sprintf("%s uintptr", p.Name)) - argsgc = append(argsgc, p.Name) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - - } else { - argscommon = append(argscommon, p.Name) - argscall = append(argscall, fmt.Sprintf("%s int", p.Name)) - argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.int(%s)", p.Name)) - } - } else if p.Type == "int32" { - argscommon = append(argscommon, p.Name) - argscall = append(argscall, fmt.Sprintf("%s int32", p.Name)) - argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.int(%s)", p.Name)) - } else if p.Type == "int64" { - argscommon = append(argscommon, p.Name) - argscall = append(argscall, fmt.Sprintf("%s int64", p.Name)) - argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.longlong(%s)", p.Name)) - } else if p.Type == "uint32" { - argscommon = append(argscommon, p.Name) - argscall = append(argscall, fmt.Sprintf("%s uint32", p.Name)) - argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uint(%s)", p.Name)) - } else if p.Type == "uint64" { - argscommon = append(argscommon, p.Name) - argscall = append(argscall, fmt.Sprintf("%s uint64", p.Name)) - argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.ulonglong(%s)", p.Name)) - } else if p.Type == "uintptr" { - argscommon = append(argscommon, p.Name) - argscall = append(argscall, fmt.Sprintf("%s uintptr", p.Name)) - argsgc = append(argsgc, p.Name) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - } else { - argscommon = append(argscommon, fmt.Sprintf("int(%s)", p.Name)) - argscall = append(argscall, fmt.Sprintf("%s int", p.Name)) - argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.int(%s)", p.Name)) - } - argN++ - } - nargs := len(argsgc) - - // COMMON function generation - argscommonlist := strings.Join(argscommon, ", ") - callcommon := fmt.Sprintf("call%s(%s)", sysname, argscommonlist) - ret := []string{"_", "_"} - body := "" - doErrno := false - for i := 0; i < len(out); i++ { - p := parseParam(out[i]) - reg := "" - if p.Name == "err" { - reg = "e1" - ret[1] = reg - doErrno = true - } else { - reg = "r0" - ret[0] = reg - } - if p.Type == "bool" { - reg = fmt.Sprintf("%s != 0", reg) - } - if reg != "e1" { - body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg) - } - } - if ret[0] == "_" && ret[1] == "_" { - textcommon += fmt.Sprintf("\t%s\n", callcommon) - } else { - textcommon += fmt.Sprintf("\t%s, %s := %s\n", ret[0], ret[1], callcommon) - } - textcommon += body - - if doErrno { - textcommon += "\tif e1 != 0 {\n" - textcommon += "\t\terr = errnoErr(e1)\n" - textcommon += "\t}\n" - } - textcommon += "\treturn\n" - textcommon += "}\n" - - if onlyCommon { - continue - } - - // CALL Prototype - callProto := fmt.Sprintf("func call%s(%s) (r1 uintptr, e1 Errno) {\n", sysname, strings.Join(argscall, ", ")) - - // GC function generation - asm := "syscall6" - if nonblock != nil { - asm = "rawSyscall6" - } - - if len(argsgc) <= 6 { - for len(argsgc) < 6 { - argsgc = append(argsgc, "0") - } - } else { - fmt.Fprintf(os.Stderr, "%s: too many arguments to system call", funct) - os.Exit(1) - } - argsgclist := strings.Join(argsgc, ", ") - callgc := fmt.Sprintf("%s(uintptr(unsafe.Pointer(&%s)), %d, %s)", asm, sysvarname, nargs, argsgclist) - - textgc += callProto - textgc += fmt.Sprintf("\tr1, _, e1 = %s\n", callgc) - textgc += "\treturn\n}\n" - - // GCCGO function generation - argsgccgolist := strings.Join(argsgccgo, ", ") - var callgccgo string - if sysname == "select" { - // select is a keyword of Go. Its name is - // changed to c_select. - callgccgo = fmt.Sprintf("C.c_%s(%s)", sysname, argsgccgolist) - } else { - callgccgo = fmt.Sprintf("C.%s(%s)", sysname, argsgccgolist) - } - textgccgo += callProto - textgccgo += fmt.Sprintf("\tr1 = uintptr(%s)\n", callgccgo) - textgccgo += "\te1 = syscall.GetErrno()\n" - textgccgo += "\treturn\n}\n" - } - if err := s.Err(); err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - file.Close() - } - imp := "" - if pack != "unix" { - imp = "import \"golang.org/x/sys/unix\"\n" - - } - - // Print zsyscall_aix_ppc64.go - err := ioutil.WriteFile("zsyscall_aix_ppc64.go", - []byte(fmt.Sprintf(srcTemplate1, cmdLine(), buildTags(), pack, imp, textcommon)), - 0644) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - - // Print zsyscall_aix_ppc64_gc.go - vardecls := "\t" + strings.Join(vars, ",\n\t") - vardecls += " syscallFunc" - err = ioutil.WriteFile("zsyscall_aix_ppc64_gc.go", - []byte(fmt.Sprintf(srcTemplate2, cmdLine(), buildTags(), pack, imp, dynimports, linknames, vardecls, textgc)), - 0644) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - - // Print zsyscall_aix_ppc64_gccgo.go - err = ioutil.WriteFile("zsyscall_aix_ppc64_gccgo.go", - []byte(fmt.Sprintf(srcTemplate3, cmdLine(), buildTags(), pack, cExtern, imp, textgccgo)), - 0644) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } -} - -const srcTemplate1 = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s - -package %s - -import ( - "unsafe" -) - - -%s - -%s -` -const srcTemplate2 = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s -// +build !gccgo - -package %s - -import ( - "unsafe" -) -%s -%s -%s -type syscallFunc uintptr - -var ( -%s -) - -// Implemented in runtime/syscall_aix.go. -func rawSyscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) -func syscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) - -%s -` -const srcTemplate3 = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s -// +build gccgo - -package %s - -%s -*/ -import "C" -import ( - "syscall" -) - - -%s - -%s -` diff --git a/vendor/golang.org/x/sys/unix/mksyscall_solaris.go b/vendor/golang.org/x/sys/unix/mksyscall_solaris.go deleted file mode 100644 index 3d864738..00000000 --- a/vendor/golang.org/x/sys/unix/mksyscall_solaris.go +++ /dev/null @@ -1,335 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* - This program reads a file containing function prototypes - (like syscall_solaris.go) and generates system call bodies. - The prototypes are marked by lines beginning with "//sys" - and read like func declarations if //sys is replaced by func, but: - * The parameter lists must give a name for each argument. - This includes return parameters. - * The parameter lists must give a type for each argument: - the (x, y, z int) shorthand is not allowed. - * If the return parameter is an error number, it must be named err. - * If go func name needs to be different than its libc name, - * or the function is not in libc, name could be specified - * at the end, after "=" sign, like - //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt -*/ - -package main - -import ( - "bufio" - "flag" - "fmt" - "os" - "regexp" - "strings" -) - -var ( - b32 = flag.Bool("b32", false, "32bit big-endian") - l32 = flag.Bool("l32", false, "32bit little-endian") - tags = flag.String("tags", "", "build tags") -) - -// cmdLine returns this programs's commandline arguments -func cmdLine() string { - return "go run mksyscall_solaris.go " + strings.Join(os.Args[1:], " ") -} - -// buildTags returns build tags -func buildTags() string { - return *tags -} - -// Param is function parameter -type Param struct { - Name string - Type string -} - -// usage prints the program usage -func usage() { - fmt.Fprintf(os.Stderr, "usage: go run mksyscall_solaris.go [-b32 | -l32] [-tags x,y] [file ...]\n") - os.Exit(1) -} - -// parseParamList parses parameter list and returns a slice of parameters -func parseParamList(list string) []string { - list = strings.TrimSpace(list) - if list == "" { - return []string{} - } - return regexp.MustCompile(`\s*,\s*`).Split(list, -1) -} - -// parseParam splits a parameter into name and type -func parseParam(p string) Param { - ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p) - if ps == nil { - fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p) - os.Exit(1) - } - return Param{ps[1], ps[2]} -} - -func main() { - flag.Usage = usage - flag.Parse() - if len(flag.Args()) <= 0 { - fmt.Fprintf(os.Stderr, "no files to parse provided\n") - usage() - } - - endianness := "" - if *b32 { - endianness = "big-endian" - } else if *l32 { - endianness = "little-endian" - } - - pack := "" - text := "" - dynimports := "" - linknames := "" - var vars []string - for _, path := range flag.Args() { - file, err := os.Open(path) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - s := bufio.NewScanner(file) - for s.Scan() { - t := s.Text() - t = strings.TrimSpace(t) - t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `) - if p := regexp.MustCompile(`^package (\S+)$`).FindStringSubmatch(t); p != nil && pack == "" { - pack = p[1] - } - nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t) - if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil { - continue - } - - // Line must be of the form - // func Open(path string, mode int, perm int) (fd int, err error) - // Split into name, in params, out params. - f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$`).FindStringSubmatch(t) - if f == nil { - fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t) - os.Exit(1) - } - funct, inps, outps, modname, sysname := f[2], f[3], f[4], f[5], f[6] - - // Split argument lists on comma. - in := parseParamList(inps) - out := parseParamList(outps) - - inps = strings.Join(in, ", ") - outps = strings.Join(out, ", ") - - // Try in vain to keep people from editing this file. - // The theory is that they jump into the middle of the file - // without reading the header. - text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n" - - // So file name. - if modname == "" { - modname = "libc" - } - - // System call name. - if sysname == "" { - sysname = funct - } - - // System call pointer variable name. - sysvarname := fmt.Sprintf("proc%s", sysname) - - strconvfunc := "BytePtrFromString" - strconvtype := "*byte" - - sysname = strings.ToLower(sysname) // All libc functions are lowercase. - - // Runtime import of function to allow cross-platform builds. - dynimports += fmt.Sprintf("//go:cgo_import_dynamic libc_%s %s \"%s.so\"\n", sysname, sysname, modname) - // Link symbol to proc address variable. - linknames += fmt.Sprintf("//go:linkname %s libc_%s\n", sysvarname, sysname) - // Library proc address variable. - vars = append(vars, sysvarname) - - // Go function header. - outlist := strings.Join(out, ", ") - if outlist != "" { - outlist = fmt.Sprintf(" (%s)", outlist) - } - if text != "" { - text += "\n" - } - text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outlist) - - // Check if err return available - errvar := "" - for _, param := range out { - p := parseParam(param) - if p.Type == "error" { - errvar = p.Name - continue - } - } - - // Prepare arguments to Syscall. - var args []string - n := 0 - for _, param := range in { - p := parseParam(param) - if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil { - args = append(args, "uintptr(unsafe.Pointer("+p.Name+"))") - } else if p.Type == "string" && errvar != "" { - text += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype) - text += fmt.Sprintf("\t_p%d, %s = %s(%s)\n", n, errvar, strconvfunc, p.Name) - text += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar) - args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) - n++ - } else if p.Type == "string" { - fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n") - text += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype) - text += fmt.Sprintf("\t_p%d, _ = %s(%s)\n", n, strconvfunc, p.Name) - args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) - n++ - } else if s := regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type); s != nil { - // Convert slice into pointer, length. - // Have to be careful not to take address of &a[0] if len == 0: - // pass nil in that case. - text += fmt.Sprintf("\tvar _p%d *%s\n", n, s[1]) - text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = &%s[0]\n\t}\n", p.Name, n, p.Name) - args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n), fmt.Sprintf("uintptr(len(%s))", p.Name)) - n++ - } else if p.Type == "int64" && endianness != "" { - if endianness == "big-endian" { - args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name)) - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name)) - } - } else if p.Type == "bool" { - text += fmt.Sprintf("\tvar _p%d uint32\n", n) - text += fmt.Sprintf("\tif %s {\n\t\t_p%d = 1\n\t} else {\n\t\t_p%d = 0\n\t}\n", p.Name, n, n) - args = append(args, fmt.Sprintf("uintptr(_p%d)", n)) - n++ - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name)) - } - } - nargs := len(args) - - // Determine which form to use; pad args with zeros. - asm := "sysvicall6" - if nonblock != nil { - asm = "rawSysvicall6" - } - if len(args) <= 6 { - for len(args) < 6 { - args = append(args, "0") - } - } else { - fmt.Fprintf(os.Stderr, "%s: too many arguments to system call\n", path) - os.Exit(1) - } - - // Actual call. - arglist := strings.Join(args, ", ") - call := fmt.Sprintf("%s(uintptr(unsafe.Pointer(&%s)), %d, %s)", asm, sysvarname, nargs, arglist) - - // Assign return values. - body := "" - ret := []string{"_", "_", "_"} - doErrno := false - for i := 0; i < len(out); i++ { - p := parseParam(out[i]) - reg := "" - if p.Name == "err" { - reg = "e1" - ret[2] = reg - doErrno = true - } else { - reg = fmt.Sprintf("r%d", i) - ret[i] = reg - } - if p.Type == "bool" { - reg = fmt.Sprintf("%d != 0", reg) - } - if p.Type == "int64" && endianness != "" { - // 64-bit number in r1:r0 or r0:r1. - if i+2 > len(out) { - fmt.Fprintf(os.Stderr, "%s: not enough registers for int64 return\n", path) - os.Exit(1) - } - if endianness == "big-endian" { - reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i, i+1) - } else { - reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i+1, i) - } - ret[i] = fmt.Sprintf("r%d", i) - ret[i+1] = fmt.Sprintf("r%d", i+1) - } - if reg != "e1" { - body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg) - } - } - if ret[0] == "_" && ret[1] == "_" && ret[2] == "_" { - text += fmt.Sprintf("\t%s\n", call) - } else { - text += fmt.Sprintf("\t%s, %s, %s := %s\n", ret[0], ret[1], ret[2], call) - } - text += body - - if doErrno { - text += "\tif e1 != 0 {\n" - text += "\t\terr = e1\n" - text += "\t}\n" - } - text += "\treturn\n" - text += "}\n" - } - if err := s.Err(); err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - file.Close() - } - imp := "" - if pack != "unix" { - imp = "import \"golang.org/x/sys/unix\"\n" - - } - vardecls := "\t" + strings.Join(vars, ",\n\t") - vardecls += " syscallFunc" - fmt.Printf(srcTemplate, cmdLine(), buildTags(), pack, imp, dynimports, linknames, vardecls, text) -} - -const srcTemplate = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s - -package %s - -import ( - "syscall" - "unsafe" -) -%s -%s -%s -var ( -%s -) - -%s -` diff --git a/vendor/golang.org/x/sys/unix/mksysctl_openbsd.go b/vendor/golang.org/x/sys/unix/mksysctl_openbsd.go deleted file mode 100644 index b6b40990..00000000 --- a/vendor/golang.org/x/sys/unix/mksysctl_openbsd.go +++ /dev/null @@ -1,355 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// Parse the header files for OpenBSD and generate a Go usable sysctl MIB. -// -// Build a MIB with each entry being an array containing the level, type and -// a hash that will contain additional entries if the current entry is a node. -// We then walk this MIB and create a flattened sysctl name to OID hash. - -package main - -import ( - "bufio" - "fmt" - "os" - "path/filepath" - "regexp" - "sort" - "strings" -) - -var ( - goos, goarch string -) - -// cmdLine returns this programs's commandline arguments. -func cmdLine() string { - return "go run mksysctl_openbsd.go " + strings.Join(os.Args[1:], " ") -} - -// buildTags returns build tags. -func buildTags() string { - return fmt.Sprintf("%s,%s", goarch, goos) -} - -// reMatch performs regular expression match and stores the substring slice to value pointed by m. -func reMatch(re *regexp.Regexp, str string, m *[]string) bool { - *m = re.FindStringSubmatch(str) - if *m != nil { - return true - } - return false -} - -type nodeElement struct { - n int - t string - pE *map[string]nodeElement -} - -var ( - debugEnabled bool - mib map[string]nodeElement - node *map[string]nodeElement - nodeMap map[string]string - sysCtl []string -) - -var ( - ctlNames1RE = regexp.MustCompile(`^#define\s+(CTL_NAMES)\s+{`) - ctlNames2RE = regexp.MustCompile(`^#define\s+(CTL_(.*)_NAMES)\s+{`) - ctlNames3RE = regexp.MustCompile(`^#define\s+((.*)CTL_NAMES)\s+{`) - netInetRE = regexp.MustCompile(`^netinet/`) - netInet6RE = regexp.MustCompile(`^netinet6/`) - netRE = regexp.MustCompile(`^net/`) - bracesRE = regexp.MustCompile(`{.*}`) - ctlTypeRE = regexp.MustCompile(`{\s+"(\w+)",\s+(CTLTYPE_[A-Z]+)\s+}`) - fsNetKernRE = regexp.MustCompile(`^(fs|net|kern)_`) -) - -func debug(s string) { - if debugEnabled { - fmt.Fprintln(os.Stderr, s) - } -} - -// Walk the MIB and build a sysctl name to OID mapping. -func buildSysctl(pNode *map[string]nodeElement, name string, oid []int) { - lNode := pNode // local copy of pointer to node - var keys []string - for k := range *lNode { - keys = append(keys, k) - } - sort.Strings(keys) - - for _, key := range keys { - nodename := name - if name != "" { - nodename += "." - } - nodename += key - - nodeoid := append(oid, (*pNode)[key].n) - - if (*pNode)[key].t == `CTLTYPE_NODE` { - if _, ok := nodeMap[nodename]; ok { - lNode = &mib - ctlName := nodeMap[nodename] - for _, part := range strings.Split(ctlName, ".") { - lNode = ((*lNode)[part]).pE - } - } else { - lNode = (*pNode)[key].pE - } - buildSysctl(lNode, nodename, nodeoid) - } else if (*pNode)[key].t != "" { - oidStr := []string{} - for j := range nodeoid { - oidStr = append(oidStr, fmt.Sprintf("%d", nodeoid[j])) - } - text := "\t{ \"" + nodename + "\", []_C_int{ " + strings.Join(oidStr, ", ") + " } }, \n" - sysCtl = append(sysCtl, text) - } - } -} - -func main() { - // Get the OS (using GOOS_TARGET if it exist) - goos = os.Getenv("GOOS_TARGET") - if goos == "" { - goos = os.Getenv("GOOS") - } - // Get the architecture (using GOARCH_TARGET if it exists) - goarch = os.Getenv("GOARCH_TARGET") - if goarch == "" { - goarch = os.Getenv("GOARCH") - } - // Check if GOOS and GOARCH environment variables are defined - if goarch == "" || goos == "" { - fmt.Fprintf(os.Stderr, "GOARCH or GOOS not defined in environment\n") - os.Exit(1) - } - - mib = make(map[string]nodeElement) - headers := [...]string{ - `sys/sysctl.h`, - `sys/socket.h`, - `sys/tty.h`, - `sys/malloc.h`, - `sys/mount.h`, - `sys/namei.h`, - `sys/sem.h`, - `sys/shm.h`, - `sys/vmmeter.h`, - `uvm/uvmexp.h`, - `uvm/uvm_param.h`, - `uvm/uvm_swap_encrypt.h`, - `ddb/db_var.h`, - `net/if.h`, - `net/if_pfsync.h`, - `net/pipex.h`, - `netinet/in.h`, - `netinet/icmp_var.h`, - `netinet/igmp_var.h`, - `netinet/ip_ah.h`, - `netinet/ip_carp.h`, - `netinet/ip_divert.h`, - `netinet/ip_esp.h`, - `netinet/ip_ether.h`, - `netinet/ip_gre.h`, - `netinet/ip_ipcomp.h`, - `netinet/ip_ipip.h`, - `netinet/pim_var.h`, - `netinet/tcp_var.h`, - `netinet/udp_var.h`, - `netinet6/in6.h`, - `netinet6/ip6_divert.h`, - `netinet6/pim6_var.h`, - `netinet/icmp6.h`, - `netmpls/mpls.h`, - } - - ctls := [...]string{ - `kern`, - `vm`, - `fs`, - `net`, - //debug /* Special handling required */ - `hw`, - //machdep /* Arch specific */ - `user`, - `ddb`, - //vfs /* Special handling required */ - `fs.posix`, - `kern.forkstat`, - `kern.intrcnt`, - `kern.malloc`, - `kern.nchstats`, - `kern.seminfo`, - `kern.shminfo`, - `kern.timecounter`, - `kern.tty`, - `kern.watchdog`, - `net.bpf`, - `net.ifq`, - `net.inet`, - `net.inet.ah`, - `net.inet.carp`, - `net.inet.divert`, - `net.inet.esp`, - `net.inet.etherip`, - `net.inet.gre`, - `net.inet.icmp`, - `net.inet.igmp`, - `net.inet.ip`, - `net.inet.ip.ifq`, - `net.inet.ipcomp`, - `net.inet.ipip`, - `net.inet.mobileip`, - `net.inet.pfsync`, - `net.inet.pim`, - `net.inet.tcp`, - `net.inet.udp`, - `net.inet6`, - `net.inet6.divert`, - `net.inet6.ip6`, - `net.inet6.icmp6`, - `net.inet6.pim6`, - `net.inet6.tcp6`, - `net.inet6.udp6`, - `net.mpls`, - `net.mpls.ifq`, - `net.key`, - `net.pflow`, - `net.pfsync`, - `net.pipex`, - `net.rt`, - `vm.swapencrypt`, - //vfsgenctl /* Special handling required */ - } - - // Node name "fixups" - ctlMap := map[string]string{ - "ipproto": "net.inet", - "net.inet.ipproto": "net.inet", - "net.inet6.ipv6proto": "net.inet6", - "net.inet6.ipv6": "net.inet6.ip6", - "net.inet.icmpv6": "net.inet6.icmp6", - "net.inet6.divert6": "net.inet6.divert", - "net.inet6.tcp6": "net.inet.tcp", - "net.inet6.udp6": "net.inet.udp", - "mpls": "net.mpls", - "swpenc": "vm.swapencrypt", - } - - // Node mappings - nodeMap = map[string]string{ - "net.inet.ip.ifq": "net.ifq", - "net.inet.pfsync": "net.pfsync", - "net.mpls.ifq": "net.ifq", - } - - mCtls := make(map[string]bool) - for _, ctl := range ctls { - mCtls[ctl] = true - } - - for _, header := range headers { - debug("Processing " + header) - file, err := os.Open(filepath.Join("/usr/include", header)) - if err != nil { - fmt.Fprintf(os.Stderr, "%v\n", err) - os.Exit(1) - } - s := bufio.NewScanner(file) - for s.Scan() { - var sub []string - if reMatch(ctlNames1RE, s.Text(), &sub) || - reMatch(ctlNames2RE, s.Text(), &sub) || - reMatch(ctlNames3RE, s.Text(), &sub) { - if sub[1] == `CTL_NAMES` { - // Top level. - node = &mib - } else { - // Node. - nodename := strings.ToLower(sub[2]) - ctlName := "" - if reMatch(netInetRE, header, &sub) { - ctlName = "net.inet." + nodename - } else if reMatch(netInet6RE, header, &sub) { - ctlName = "net.inet6." + nodename - } else if reMatch(netRE, header, &sub) { - ctlName = "net." + nodename - } else { - ctlName = nodename - ctlName = fsNetKernRE.ReplaceAllString(ctlName, `$1.`) - } - - if val, ok := ctlMap[ctlName]; ok { - ctlName = val - } - if _, ok := mCtls[ctlName]; !ok { - debug("Ignoring " + ctlName + "...") - continue - } - - // Walk down from the top of the MIB. - node = &mib - for _, part := range strings.Split(ctlName, ".") { - if _, ok := (*node)[part]; !ok { - debug("Missing node " + part) - (*node)[part] = nodeElement{n: 0, t: "", pE: &map[string]nodeElement{}} - } - node = (*node)[part].pE - } - } - - // Populate current node with entries. - i := -1 - for !strings.HasPrefix(s.Text(), "}") { - s.Scan() - if reMatch(bracesRE, s.Text(), &sub) { - i++ - } - if !reMatch(ctlTypeRE, s.Text(), &sub) { - continue - } - (*node)[sub[1]] = nodeElement{n: i, t: sub[2], pE: &map[string]nodeElement{}} - } - } - } - err = s.Err() - if err != nil { - fmt.Fprintf(os.Stderr, "%v\n", err) - os.Exit(1) - } - file.Close() - } - buildSysctl(&mib, "", []int{}) - - sort.Strings(sysCtl) - text := strings.Join(sysCtl, "") - - fmt.Printf(srcTemplate, cmdLine(), buildTags(), text) -} - -const srcTemplate = `// %s -// Code generated by the command above; DO NOT EDIT. - -// +build %s - -package unix - -type mibentry struct { - ctlname string - ctloid []_C_int -} - -var sysctlMib = []mibentry { -%s -} -` diff --git a/vendor/golang.org/x/sys/unix/mksysnum.go b/vendor/golang.org/x/sys/unix/mksysnum.go deleted file mode 100644 index baa6ecd8..00000000 --- a/vendor/golang.org/x/sys/unix/mksysnum.go +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// Generate system call table for DragonFly, NetBSD, -// FreeBSD, OpenBSD or Darwin from master list -// (for example, /usr/src/sys/kern/syscalls.master or -// sys/syscall.h). -package main - -import ( - "bufio" - "fmt" - "io" - "io/ioutil" - "net/http" - "os" - "regexp" - "strings" -) - -var ( - goos, goarch string -) - -// cmdLine returns this programs's commandline arguments -func cmdLine() string { - return "go run mksysnum.go " + strings.Join(os.Args[1:], " ") -} - -// buildTags returns build tags -func buildTags() string { - return fmt.Sprintf("%s,%s", goarch, goos) -} - -func checkErr(err error) { - if err != nil { - fmt.Fprintf(os.Stderr, "%v\n", err) - os.Exit(1) - } -} - -// source string and substring slice for regexp -type re struct { - str string // source string - sub []string // matched sub-string -} - -// Match performs regular expression match -func (r *re) Match(exp string) bool { - r.sub = regexp.MustCompile(exp).FindStringSubmatch(r.str) - if r.sub != nil { - return true - } - return false -} - -// fetchFile fetches a text file from URL -func fetchFile(URL string) io.Reader { - resp, err := http.Get(URL) - checkErr(err) - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - checkErr(err) - return strings.NewReader(string(body)) -} - -// readFile reads a text file from path -func readFile(path string) io.Reader { - file, err := os.Open(os.Args[1]) - checkErr(err) - return file -} - -func format(name, num, proto string) string { - name = strings.ToUpper(name) - // There are multiple entries for enosys and nosys, so comment them out. - nm := re{str: name} - if nm.Match(`^SYS_E?NOSYS$`) { - name = fmt.Sprintf("// %s", name) - } - if name == `SYS_SYS_EXIT` { - name = `SYS_EXIT` - } - return fmt.Sprintf(" %s = %s; // %s\n", name, num, proto) -} - -func main() { - // Get the OS (using GOOS_TARGET if it exist) - goos = os.Getenv("GOOS_TARGET") - if goos == "" { - goos = os.Getenv("GOOS") - } - // Get the architecture (using GOARCH_TARGET if it exists) - goarch = os.Getenv("GOARCH_TARGET") - if goarch == "" { - goarch = os.Getenv("GOARCH") - } - // Check if GOOS and GOARCH environment variables are defined - if goarch == "" || goos == "" { - fmt.Fprintf(os.Stderr, "GOARCH or GOOS not defined in environment\n") - os.Exit(1) - } - - file := strings.TrimSpace(os.Args[1]) - var syscalls io.Reader - if strings.HasPrefix(file, "https://") || strings.HasPrefix(file, "http://") { - // Download syscalls.master file - syscalls = fetchFile(file) - } else { - syscalls = readFile(file) - } - - var text, line string - s := bufio.NewScanner(syscalls) - for s.Scan() { - t := re{str: line} - if t.Match(`^(.*)\\$`) { - // Handle continuation - line = t.sub[1] - line += strings.TrimLeft(s.Text(), " \t") - } else { - // New line - line = s.Text() - } - t = re{str: line} - if t.Match(`\\$`) { - continue - } - t = re{str: line} - - switch goos { - case "dragonfly": - if t.Match(`^([0-9]+)\s+STD\s+({ \S+\s+(\w+).*)$`) { - num, proto := t.sub[1], t.sub[2] - name := fmt.Sprintf("SYS_%s", t.sub[3]) - text += format(name, num, proto) - } - case "freebsd": - if t.Match(`^([0-9]+)\s+\S+\s+(?:(?:NO)?STD|COMPAT10)\s+({ \S+\s+(\w+).*)$`) { - num, proto := t.sub[1], t.sub[2] - name := fmt.Sprintf("SYS_%s", t.sub[3]) - text += format(name, num, proto) - } - case "openbsd": - if t.Match(`^([0-9]+)\s+STD\s+(NOLOCK\s+)?({ \S+\s+\*?(\w+).*)$`) { - num, proto, name := t.sub[1], t.sub[3], t.sub[4] - text += format(name, num, proto) - } - case "netbsd": - if t.Match(`^([0-9]+)\s+((STD)|(NOERR))\s+(RUMP\s+)?({\s+\S+\s*\*?\s*\|(\S+)\|(\S*)\|(\w+).*\s+})(\s+(\S+))?$`) { - num, proto, compat := t.sub[1], t.sub[6], t.sub[8] - name := t.sub[7] + "_" + t.sub[9] - if t.sub[11] != "" { - name = t.sub[7] + "_" + t.sub[11] - } - name = strings.ToUpper(name) - if compat == "" || compat == "13" || compat == "30" || compat == "50" { - text += fmt.Sprintf(" %s = %s; // %s\n", name, num, proto) - } - } - case "darwin": - if t.Match(`^#define\s+SYS_(\w+)\s+([0-9]+)`) { - name, num := t.sub[1], t.sub[2] - name = strings.ToUpper(name) - text += fmt.Sprintf(" SYS_%s = %s;\n", name, num) - } - default: - fmt.Fprintf(os.Stderr, "unrecognized GOOS=%s\n", goos) - os.Exit(1) - - } - } - err := s.Err() - checkErr(err) - - fmt.Printf(template, cmdLine(), buildTags(), text) -} - -const template = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s - -package unix - -const( -%s)` diff --git a/vendor/golang.org/x/sys/unix/types_aix.go b/vendor/golang.org/x/sys/unix/types_aix.go deleted file mode 100644 index 40d2beed..00000000 --- a/vendor/golang.org/x/sys/unix/types_aix.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore -// +build aix - -/* -Input to cgo -godefs. See also mkerrors.sh and mkall.sh -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include - - -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong - PathMax = C.PATH_MAX -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -type off64 C.off64_t -type off C.off_t -type Mode_t C.mode_t - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -type Timeval32 C.struct_timeval32 - -type Timex C.struct_timex - -type Time_t C.time_t - -type Tms C.struct_tms - -type Utimbuf C.struct_utimbuf - -type Timezone C.struct_timezone - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit64 - -type Pid_t C.pid_t - -type _Gid_t C.gid_t - -type dev_t C.dev_t - -// Files - -type Stat_t C.struct_stat - -type StatxTimestamp C.struct_statx_timestamp - -type Statx_t C.struct_statx - -type Dirent C.struct_dirent - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Cmsghdr C.struct_cmsghdr - -type ICMPv6Filter C.struct_icmp6_filter - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type Linger C.struct_linger - -type Msghdr C.struct_msghdr - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr -) - -type IfMsgHdr C.struct_if_msghdr - -// Misc - -type FdSet C.fd_set - -type Utsname C.struct_utsname - -type Ustat_t C.struct_ustat - -type Sigset_t C.sigset_t - -const ( - AT_FDCWD = C.AT_FDCWD - AT_REMOVEDIR = C.AT_REMOVEDIR - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) - -// Terminal handling - -type Termios C.struct_termios - -type Termio C.struct_termio - -type Winsize C.struct_winsize - -//poll - -type PollFd struct { - Fd int32 - Events uint16 - Revents uint16 -} - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) - -//flock_t - -type Flock_t C.struct_flock64 - -// Statfs - -type Fsid_t C.struct_fsid_t -type Fsid64_t C.struct_fsid64_t - -type Statfs_t C.struct_statfs - -const RNDGETENTCNT = 0x80045200 diff --git a/vendor/golang.org/x/sys/unix/types_darwin.go b/vendor/golang.org/x/sys/unix/types_darwin.go deleted file mode 100644 index 155c2e69..00000000 --- a/vendor/golang.org/x/sys/unix/types_darwin.go +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See README.md -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define __DARWIN_UNIX03 0 -#define KERNEL -#define _DARWIN_USE_64_BIT_INODE -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -type Timeval32 C.struct_timeval32 - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -type Stat_t C.struct_stat64 - -type Statfs_t C.struct_statfs64 - -type Flock_t C.struct_flock - -type Fstore_t C.struct_fstore - -type Radvisory_t C.struct_radvisory - -type Fbootstraptransfer_t C.struct_fbootstraptransfer - -type Log2phys_t C.struct_log2phys - -type Fsid C.struct_fsid - -type Dirent C.struct_dirent - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet4Pktinfo C.struct_in_pktinfo - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet4Pktinfo = C.sizeof_struct_in_pktinfo - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_TRACEME = C.PT_TRACE_ME - PTRACE_CONT = C.PT_CONTINUE - PTRACE_KILL = C.PT_KILL -) - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr - SizeofIfmaMsghdr2 = C.sizeof_struct_ifma_msghdr2 - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type IfmaMsghdr C.struct_ifma_msghdr - -type IfmaMsghdr2 C.struct_ifma_msghdr2 - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -// Terminal handling - -type Termios C.struct_termios - -type Winsize C.struct_winsize - -// fchmodat-like syscalls. - -const ( - AT_FDCWD = C.AT_FDCWD - AT_REMOVEDIR = C.AT_REMOVEDIR - AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) - -// poll - -type PollFd C.struct_pollfd - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) - -// uname - -type Utsname C.struct_utsname - -// Clockinfo - -const SizeofClockinfo = C.sizeof_struct_clockinfo - -type Clockinfo C.struct_clockinfo diff --git a/vendor/golang.org/x/sys/unix/types_dragonfly.go b/vendor/golang.org/x/sys/unix/types_dragonfly.go deleted file mode 100644 index 3365dd79..00000000 --- a/vendor/golang.org/x/sys/unix/types_dragonfly.go +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See README.md -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define KERNEL -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -type Stat_t C.struct_stat - -type Statfs_t C.struct_statfs - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -type Fsid C.struct_fsid - -// File system limits - -const ( - PathMax = C.PATH_MAX -) - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_TRACEME = C.PT_TRACE_ME - PTRACE_CONT = C.PT_CONTINUE - PTRACE_KILL = C.PT_KILL -) - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr - SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type IfmaMsghdr C.struct_ifma_msghdr - -type IfAnnounceMsghdr C.struct_if_announcemsghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -// Terminal handling - -type Termios C.struct_termios - -type Winsize C.struct_winsize - -// fchmodat-like syscalls. - -const ( - AT_FDCWD = C.AT_FDCWD - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) - -// poll - -type PollFd C.struct_pollfd - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) - -// Uname - -type Utsname C.struct_utsname diff --git a/vendor/golang.org/x/sys/unix/types_freebsd.go b/vendor/golang.org/x/sys/unix/types_freebsd.go deleted file mode 100644 index a121dc33..00000000 --- a/vendor/golang.org/x/sys/unix/types_freebsd.go +++ /dev/null @@ -1,400 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See README.md -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define _WANT_FREEBSD11_STAT 1 -#define _WANT_FREEBSD11_STATFS 1 -#define _WANT_FREEBSD11_DIRENT 1 -#define _WANT_FREEBSD11_KEVENT 1 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -// This structure is a duplicate of if_data on FreeBSD 8-STABLE. -// See /usr/include/net/if.h. -struct if_data8 { - u_char ifi_type; - u_char ifi_physical; - u_char ifi_addrlen; - u_char ifi_hdrlen; - u_char ifi_link_state; - u_char ifi_spare_char1; - u_char ifi_spare_char2; - u_char ifi_datalen; - u_long ifi_mtu; - u_long ifi_metric; - u_long ifi_baudrate; - u_long ifi_ipackets; - u_long ifi_ierrors; - u_long ifi_opackets; - u_long ifi_oerrors; - u_long ifi_collisions; - u_long ifi_ibytes; - u_long ifi_obytes; - u_long ifi_imcasts; - u_long ifi_omcasts; - u_long ifi_iqdrops; - u_long ifi_noproto; - u_long ifi_hwassist; -// FIXME: these are now unions, so maybe need to change definitions? -#undef ifi_epoch - time_t ifi_epoch; -#undef ifi_lastchange - struct timeval ifi_lastchange; -}; - -// This structure is a duplicate of if_msghdr on FreeBSD 8-STABLE. -// See /usr/include/net/if.h. -struct if_msghdr8 { - u_short ifm_msglen; - u_char ifm_version; - u_char ifm_type; - int ifm_addrs; - int ifm_flags; - u_short ifm_index; - struct if_data8 ifm_data; -}; -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -const ( - _statfsVersion = C.STATFS_VERSION - _dirblksiz = C.DIRBLKSIZ -) - -type Stat_t C.struct_stat - -type stat_freebsd11_t C.struct_freebsd11_stat - -type Statfs_t C.struct_statfs - -type statfs_freebsd11_t C.struct_freebsd11_statfs - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -type dirent_freebsd11 C.struct_freebsd11_dirent - -type Fsid C.struct_fsid - -// File system limits - -const ( - PathMax = C.PATH_MAX -) - -// Advice to Fadvise - -const ( - FADV_NORMAL = C.POSIX_FADV_NORMAL - FADV_RANDOM = C.POSIX_FADV_RANDOM - FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL - FADV_WILLNEED = C.POSIX_FADV_WILLNEED - FADV_DONTNEED = C.POSIX_FADV_DONTNEED - FADV_NOREUSE = C.POSIX_FADV_NOREUSE -) - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPMreqn C.struct_ip_mreqn - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPMreqn = C.sizeof_struct_ip_mreqn - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_ATTACH = C.PT_ATTACH - PTRACE_CONT = C.PT_CONTINUE - PTRACE_DETACH = C.PT_DETACH - PTRACE_GETFPREGS = C.PT_GETFPREGS - PTRACE_GETFSBASE = C.PT_GETFSBASE - PTRACE_GETLWPLIST = C.PT_GETLWPLIST - PTRACE_GETNUMLWPS = C.PT_GETNUMLWPS - PTRACE_GETREGS = C.PT_GETREGS - PTRACE_GETXSTATE = C.PT_GETXSTATE - PTRACE_IO = C.PT_IO - PTRACE_KILL = C.PT_KILL - PTRACE_LWPEVENTS = C.PT_LWP_EVENTS - PTRACE_LWPINFO = C.PT_LWPINFO - PTRACE_SETFPREGS = C.PT_SETFPREGS - PTRACE_SETREGS = C.PT_SETREGS - PTRACE_SINGLESTEP = C.PT_STEP - PTRACE_TRACEME = C.PT_TRACE_ME -) - -const ( - PIOD_READ_D = C.PIOD_READ_D - PIOD_WRITE_D = C.PIOD_WRITE_D - PIOD_READ_I = C.PIOD_READ_I - PIOD_WRITE_I = C.PIOD_WRITE_I -) - -const ( - PL_FLAG_BORN = C.PL_FLAG_BORN - PL_FLAG_EXITED = C.PL_FLAG_EXITED - PL_FLAG_SI = C.PL_FLAG_SI -) - -const ( - TRAP_BRKPT = C.TRAP_BRKPT - TRAP_TRACE = C.TRAP_TRACE -) - -type PtraceLwpInfoStruct C.struct_ptrace_lwpinfo - -type __Siginfo C.struct___siginfo - -type Sigset_t C.sigset_t - -type Reg C.struct_reg - -type FpReg C.struct_fpreg - -type PtraceIoDesc C.struct_ptrace_io_desc - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent_freebsd11 - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - sizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfMsghdr = C.sizeof_struct_if_msghdr8 - sizeofIfData = C.sizeof_struct_if_data - SizeofIfData = C.sizeof_struct_if_data8 - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr - SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type ifMsghdr C.struct_if_msghdr - -type IfMsghdr C.struct_if_msghdr8 - -type ifData C.struct_if_data - -type IfData C.struct_if_data8 - -type IfaMsghdr C.struct_ifa_msghdr - -type IfmaMsghdr C.struct_ifma_msghdr - -type IfAnnounceMsghdr C.struct_if_announcemsghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfZbuf = C.sizeof_struct_bpf_zbuf - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr - SizeofBpfZbufHeader = C.sizeof_struct_bpf_zbuf_header -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfZbuf C.struct_bpf_zbuf - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -type BpfZbufHeader C.struct_bpf_zbuf_header - -// Terminal handling - -type Termios C.struct_termios - -type Winsize C.struct_winsize - -// fchmodat-like syscalls. - -const ( - AT_FDCWD = C.AT_FDCWD - AT_REMOVEDIR = C.AT_REMOVEDIR - AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) - -// poll - -type PollFd C.struct_pollfd - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLINIGNEOF = C.POLLINIGNEOF - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) - -// Capabilities - -type CapRights C.struct_cap_rights - -// Uname - -type Utsname C.struct_utsname diff --git a/vendor/golang.org/x/sys/unix/types_netbsd.go b/vendor/golang.org/x/sys/unix/types_netbsd.go deleted file mode 100644 index 4a96d72c..00000000 --- a/vendor/golang.org/x/sys/unix/types_netbsd.go +++ /dev/null @@ -1,290 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See README.md -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define KERNEL -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -type Stat_t C.struct_stat - -type Statfs_t C.struct_statfs - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -type Fsid C.fsid_t - -// File system limits - -const ( - PathMax = C.PATH_MAX -) - -// Advice to Fadvise - -const ( - FADV_NORMAL = C.POSIX_FADV_NORMAL - FADV_RANDOM = C.POSIX_FADV_RANDOM - FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL - FADV_WILLNEED = C.POSIX_FADV_WILLNEED - FADV_DONTNEED = C.POSIX_FADV_DONTNEED - FADV_NOREUSE = C.POSIX_FADV_NOREUSE -) - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_TRACEME = C.PT_TRACE_ME - PTRACE_CONT = C.PT_CONTINUE - PTRACE_KILL = C.PT_KILL -) - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type IfAnnounceMsghdr C.struct_if_announcemsghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -type Mclpool C.struct_mclpool - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -type BpfTimeval C.struct_bpf_timeval - -// Terminal handling - -type Termios C.struct_termios - -type Winsize C.struct_winsize - -type Ptmget C.struct_ptmget - -// fchmodat-like syscalls. - -const ( - AT_FDCWD = C.AT_FDCWD - AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) - -// poll - -type PollFd C.struct_pollfd - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) - -// Sysctl - -type Sysctlnode C.struct_sysctlnode - -// Uname - -type Utsname C.struct_utsname - -// Clockinfo - -const SizeofClockinfo = C.sizeof_struct_clockinfo - -type Clockinfo C.struct_clockinfo diff --git a/vendor/golang.org/x/sys/unix/types_openbsd.go b/vendor/golang.org/x/sys/unix/types_openbsd.go deleted file mode 100644 index 775cb57d..00000000 --- a/vendor/golang.org/x/sys/unix/types_openbsd.go +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See README.md -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define KERNEL -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -type Stat_t C.struct_stat - -type Statfs_t C.struct_statfs - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -type Fsid C.fsid_t - -// File system limits - -const ( - PathMax = C.PATH_MAX -) - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_TRACEME = C.PT_TRACE_ME - PTRACE_CONT = C.PT_CONTINUE - PTRACE_KILL = C.PT_KILL -) - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type IfAnnounceMsghdr C.struct_if_announcemsghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -type Mclpool C.struct_mclpool - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -type BpfTimeval C.struct_bpf_timeval - -// Terminal handling - -type Termios C.struct_termios - -type Winsize C.struct_winsize - -// fchmodat-like syscalls. - -const ( - AT_FDCWD = C.AT_FDCWD - AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) - -// poll - -type PollFd C.struct_pollfd - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) - -// Signal Sets - -type Sigset_t C.sigset_t - -// Uname - -type Utsname C.struct_utsname - -// Uvmexp - -const SizeofUvmexp = C.sizeof_struct_uvmexp - -type Uvmexp C.struct_uvmexp - -// Clockinfo - -const SizeofClockinfo = C.sizeof_struct_clockinfo - -type Clockinfo C.struct_clockinfo diff --git a/vendor/golang.org/x/sys/unix/types_solaris.go b/vendor/golang.org/x/sys/unix/types_solaris.go deleted file mode 100644 index 2b716f93..00000000 --- a/vendor/golang.org/x/sys/unix/types_solaris.go +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See README.md -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define KERNEL -// These defines ensure that builds done on newer versions of Solaris are -// backwards-compatible with older versions of Solaris and -// OpenSolaris-based derivatives. -#define __USE_SUNOS_SOCKETS__ // msghdr -#define __USE_LEGACY_PROTOTYPES__ // iovec -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong - PathMax = C.PATH_MAX - MaxHostNameLen = C.MAXHOSTNAMELEN -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -type Timeval32 C.struct_timeval32 - -type Tms C.struct_tms - -type Utimbuf C.struct_utimbuf - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -type Stat_t C.struct_stat - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -// Filesystems - -type _Fsblkcnt_t C.fsblkcnt_t - -type Statvfs_t C.struct_statvfs - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Select - -type FdSet C.fd_set - -// Misc - -type Utsname C.struct_utsname - -type Ustat_t C.struct_ustat - -const ( - AT_FDCWD = C.AT_FDCWD - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW - AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW - AT_REMOVEDIR = C.AT_REMOVEDIR - AT_EACCESS = C.AT_EACCESS -) - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfTimeval C.struct_bpf_timeval - -type BpfHdr C.struct_bpf_hdr - -// Terminal handling - -type Termios C.struct_termios - -type Termio C.struct_termio - -type Winsize C.struct_winsize - -// poll - -type PollFd C.struct_pollfd - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) diff --git a/vendor/golang.org/x/text/unicode/bidi/gen.go b/vendor/golang.org/x/text/unicode/bidi/gen.go deleted file mode 100644 index 987fc169..00000000 --- a/vendor/golang.org/x/text/unicode/bidi/gen.go +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "flag" - "log" - - "golang.org/x/text/internal/gen" - "golang.org/x/text/internal/triegen" - "golang.org/x/text/internal/ucd" -) - -var outputFile = flag.String("out", "tables.go", "output file") - -func main() { - gen.Init() - gen.Repackage("gen_trieval.go", "trieval.go", "bidi") - gen.Repackage("gen_ranges.go", "ranges_test.go", "bidi") - - genTables() -} - -// bidiClass names and codes taken from class "bc" in -// https://www.unicode.org/Public/8.0.0/ucd/PropertyValueAliases.txt -var bidiClass = map[string]Class{ - "AL": AL, // ArabicLetter - "AN": AN, // ArabicNumber - "B": B, // ParagraphSeparator - "BN": BN, // BoundaryNeutral - "CS": CS, // CommonSeparator - "EN": EN, // EuropeanNumber - "ES": ES, // EuropeanSeparator - "ET": ET, // EuropeanTerminator - "L": L, // LeftToRight - "NSM": NSM, // NonspacingMark - "ON": ON, // OtherNeutral - "R": R, // RightToLeft - "S": S, // SegmentSeparator - "WS": WS, // WhiteSpace - - "FSI": Control, - "PDF": Control, - "PDI": Control, - "LRE": Control, - "LRI": Control, - "LRO": Control, - "RLE": Control, - "RLI": Control, - "RLO": Control, -} - -func genTables() { - if numClass > 0x0F { - log.Fatalf("Too many Class constants (%#x > 0x0F).", numClass) - } - w := gen.NewCodeWriter() - defer w.WriteVersionedGoFile(*outputFile, "bidi") - - gen.WriteUnicodeVersion(w) - - t := triegen.NewTrie("bidi") - - // Build data about bracket mapping. These bits need to be or-ed with - // any other bits. - orMask := map[rune]uint64{} - - xorMap := map[rune]int{} - xorMasks := []rune{0} // First value is no-op. - - ucd.Parse(gen.OpenUCDFile("BidiBrackets.txt"), func(p *ucd.Parser) { - r1 := p.Rune(0) - r2 := p.Rune(1) - xor := r1 ^ r2 - if _, ok := xorMap[xor]; !ok { - xorMap[xor] = len(xorMasks) - xorMasks = append(xorMasks, xor) - } - entry := uint64(xorMap[xor]) << xorMaskShift - switch p.String(2) { - case "o": - entry |= openMask - case "c", "n": - default: - log.Fatalf("Unknown bracket class %q.", p.String(2)) - } - orMask[r1] = entry - }) - - w.WriteComment(` - xorMasks contains masks to be xor-ed with brackets to get the reverse - version.`) - w.WriteVar("xorMasks", xorMasks) - - done := map[rune]bool{} - - insert := func(r rune, c Class) { - if !done[r] { - t.Insert(r, orMask[r]|uint64(c)) - done[r] = true - } - } - - // Insert the derived BiDi properties. - ucd.Parse(gen.OpenUCDFile("extracted/DerivedBidiClass.txt"), func(p *ucd.Parser) { - r := p.Rune(0) - class, ok := bidiClass[p.String(1)] - if !ok { - log.Fatalf("%U: Unknown BiDi class %q", r, p.String(1)) - } - insert(r, class) - }) - visitDefaults(insert) - - // TODO: use sparse blocks. This would reduce table size considerably - // from the looks of it. - - sz, err := t.Gen(w) - if err != nil { - log.Fatal(err) - } - w.Size += sz -} - -// dummy values to make methods in gen_common compile. The real versions -// will be generated by this file to tables.go. -var ( - xorMasks []rune -) diff --git a/vendor/golang.org/x/text/unicode/bidi/gen_ranges.go b/vendor/golang.org/x/text/unicode/bidi/gen_ranges.go deleted file mode 100644 index 02c3b505..00000000 --- a/vendor/golang.org/x/text/unicode/bidi/gen_ranges.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "unicode" - - "golang.org/x/text/internal/gen" - "golang.org/x/text/internal/ucd" - "golang.org/x/text/unicode/rangetable" -) - -// These tables are hand-extracted from: -// https://www.unicode.org/Public/8.0.0/ucd/extracted/DerivedBidiClass.txt -func visitDefaults(fn func(r rune, c Class)) { - // first write default values for ranges listed above. - visitRunes(fn, AL, []rune{ - 0x0600, 0x07BF, // Arabic - 0x08A0, 0x08FF, // Arabic Extended-A - 0xFB50, 0xFDCF, // Arabic Presentation Forms - 0xFDF0, 0xFDFF, - 0xFE70, 0xFEFF, - 0x0001EE00, 0x0001EEFF, // Arabic Mathematical Alpha Symbols - }) - visitRunes(fn, R, []rune{ - 0x0590, 0x05FF, // Hebrew - 0x07C0, 0x089F, // Nko et al. - 0xFB1D, 0xFB4F, - 0x00010800, 0x00010FFF, // Cypriot Syllabary et. al. - 0x0001E800, 0x0001EDFF, - 0x0001EF00, 0x0001EFFF, - }) - visitRunes(fn, ET, []rune{ // European Terminator - 0x20A0, 0x20Cf, // Currency symbols - }) - rangetable.Visit(unicode.Noncharacter_Code_Point, func(r rune) { - fn(r, BN) // Boundary Neutral - }) - ucd.Parse(gen.OpenUCDFile("DerivedCoreProperties.txt"), func(p *ucd.Parser) { - if p.String(1) == "Default_Ignorable_Code_Point" { - fn(p.Rune(0), BN) // Boundary Neutral - } - }) -} - -func visitRunes(fn func(r rune, c Class), c Class, runes []rune) { - for i := 0; i < len(runes); i += 2 { - lo, hi := runes[i], runes[i+1] - for j := lo; j <= hi; j++ { - fn(j, c) - } - } -} diff --git a/vendor/golang.org/x/text/unicode/bidi/gen_trieval.go b/vendor/golang.org/x/text/unicode/bidi/gen_trieval.go deleted file mode 100644 index 9cb99428..00000000 --- a/vendor/golang.org/x/text/unicode/bidi/gen_trieval.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -// Class is the Unicode BiDi class. Each rune has a single class. -type Class uint - -const ( - L Class = iota // LeftToRight - R // RightToLeft - EN // EuropeanNumber - ES // EuropeanSeparator - ET // EuropeanTerminator - AN // ArabicNumber - CS // CommonSeparator - B // ParagraphSeparator - S // SegmentSeparator - WS // WhiteSpace - ON // OtherNeutral - BN // BoundaryNeutral - NSM // NonspacingMark - AL // ArabicLetter - Control // Control LRO - PDI - - numClass - - LRO // LeftToRightOverride - RLO // RightToLeftOverride - LRE // LeftToRightEmbedding - RLE // RightToLeftEmbedding - PDF // PopDirectionalFormat - LRI // LeftToRightIsolate - RLI // RightToLeftIsolate - FSI // FirstStrongIsolate - PDI // PopDirectionalIsolate - - unknownClass = ^Class(0) -) - -var controlToClass = map[rune]Class{ - 0x202D: LRO, // LeftToRightOverride, - 0x202E: RLO, // RightToLeftOverride, - 0x202A: LRE, // LeftToRightEmbedding, - 0x202B: RLE, // RightToLeftEmbedding, - 0x202C: PDF, // PopDirectionalFormat, - 0x2066: LRI, // LeftToRightIsolate, - 0x2067: RLI, // RightToLeftIsolate, - 0x2068: FSI, // FirstStrongIsolate, - 0x2069: PDI, // PopDirectionalIsolate, -} - -// A trie entry has the following bits: -// 7..5 XOR mask for brackets -// 4 1: Bracket open, 0: Bracket close -// 3..0 Class type - -const ( - openMask = 0x10 - xorMaskShift = 5 -) diff --git a/vendor/golang.org/x/text/unicode/norm/maketables.go b/vendor/golang.org/x/text/unicode/norm/maketables.go deleted file mode 100644 index 30a3aa93..00000000 --- a/vendor/golang.org/x/text/unicode/norm/maketables.go +++ /dev/null @@ -1,986 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// Normalization table generator. -// Data read from the web. -// See forminfo.go for a description of the trie values associated with each rune. - -package main - -import ( - "bytes" - "encoding/binary" - "flag" - "fmt" - "io" - "log" - "sort" - "strconv" - "strings" - - "golang.org/x/text/internal/gen" - "golang.org/x/text/internal/triegen" - "golang.org/x/text/internal/ucd" -) - -func main() { - gen.Init() - loadUnicodeData() - compactCCC() - loadCompositionExclusions() - completeCharFields(FCanonical) - completeCharFields(FCompatibility) - computeNonStarterCounts() - verifyComputed() - printChars() - testDerived() - printTestdata() - makeTables() -} - -var ( - tablelist = flag.String("tables", - "all", - "comma-separated list of which tables to generate; "+ - "can be 'decomp', 'recomp', 'info' and 'all'") - test = flag.Bool("test", - false, - "test existing tables against DerivedNormalizationProps and generate test data for regression testing") - verbose = flag.Bool("verbose", - false, - "write data to stdout as it is parsed") -) - -const MaxChar = 0x10FFFF // anything above this shouldn't exist - -// Quick Check properties of runes allow us to quickly -// determine whether a rune may occur in a normal form. -// For a given normal form, a rune may be guaranteed to occur -// verbatim (QC=Yes), may or may not combine with another -// rune (QC=Maybe), or may not occur (QC=No). -type QCResult int - -const ( - QCUnknown QCResult = iota - QCYes - QCNo - QCMaybe -) - -func (r QCResult) String() string { - switch r { - case QCYes: - return "Yes" - case QCNo: - return "No" - case QCMaybe: - return "Maybe" - } - return "***UNKNOWN***" -} - -const ( - FCanonical = iota // NFC or NFD - FCompatibility // NFKC or NFKD - FNumberOfFormTypes -) - -const ( - MComposed = iota // NFC or NFKC - MDecomposed // NFD or NFKD - MNumberOfModes -) - -// This contains only the properties we're interested in. -type Char struct { - name string - codePoint rune // if zero, this index is not a valid code point. - ccc uint8 // canonical combining class - origCCC uint8 - excludeInComp bool // from CompositionExclusions.txt - compatDecomp bool // it has a compatibility expansion - - nTrailingNonStarters uint8 - nLeadingNonStarters uint8 // must be equal to trailing if non-zero - - forms [FNumberOfFormTypes]FormInfo // For FCanonical and FCompatibility - - state State -} - -var chars = make([]Char, MaxChar+1) -var cccMap = make(map[uint8]uint8) - -func (c Char) String() string { - buf := new(bytes.Buffer) - - fmt.Fprintf(buf, "%U [%s]:\n", c.codePoint, c.name) - fmt.Fprintf(buf, " ccc: %v\n", c.ccc) - fmt.Fprintf(buf, " excludeInComp: %v\n", c.excludeInComp) - fmt.Fprintf(buf, " compatDecomp: %v\n", c.compatDecomp) - fmt.Fprintf(buf, " state: %v\n", c.state) - fmt.Fprintf(buf, " NFC:\n") - fmt.Fprint(buf, c.forms[FCanonical]) - fmt.Fprintf(buf, " NFKC:\n") - fmt.Fprint(buf, c.forms[FCompatibility]) - - return buf.String() -} - -// In UnicodeData.txt, some ranges are marked like this: -// 3400;;Lo;0;L;;;;;N;;;;; -// 4DB5;;Lo;0;L;;;;;N;;;;; -// parseCharacter keeps a state variable indicating the weirdness. -type State int - -const ( - SNormal State = iota // known to be zero for the type - SFirst - SLast - SMissing -) - -var lastChar = rune('\u0000') - -func (c Char) isValid() bool { - return c.codePoint != 0 && c.state != SMissing -} - -type FormInfo struct { - quickCheck [MNumberOfModes]QCResult // index: MComposed or MDecomposed - verified [MNumberOfModes]bool // index: MComposed or MDecomposed - - combinesForward bool // May combine with rune on the right - combinesBackward bool // May combine with rune on the left - isOneWay bool // Never appears in result - inDecomp bool // Some decompositions result in this char. - decomp Decomposition - expandedDecomp Decomposition -} - -func (f FormInfo) String() string { - buf := bytes.NewBuffer(make([]byte, 0)) - - fmt.Fprintf(buf, " quickCheck[C]: %v\n", f.quickCheck[MComposed]) - fmt.Fprintf(buf, " quickCheck[D]: %v\n", f.quickCheck[MDecomposed]) - fmt.Fprintf(buf, " cmbForward: %v\n", f.combinesForward) - fmt.Fprintf(buf, " cmbBackward: %v\n", f.combinesBackward) - fmt.Fprintf(buf, " isOneWay: %v\n", f.isOneWay) - fmt.Fprintf(buf, " inDecomp: %v\n", f.inDecomp) - fmt.Fprintf(buf, " decomposition: %X\n", f.decomp) - fmt.Fprintf(buf, " expandedDecomp: %X\n", f.expandedDecomp) - - return buf.String() -} - -type Decomposition []rune - -func parseDecomposition(s string, skipfirst bool) (a []rune, err error) { - decomp := strings.Split(s, " ") - if len(decomp) > 0 && skipfirst { - decomp = decomp[1:] - } - for _, d := range decomp { - point, err := strconv.ParseUint(d, 16, 64) - if err != nil { - return a, err - } - a = append(a, rune(point)) - } - return a, nil -} - -func loadUnicodeData() { - f := gen.OpenUCDFile("UnicodeData.txt") - defer f.Close() - p := ucd.New(f) - for p.Next() { - r := p.Rune(ucd.CodePoint) - char := &chars[r] - - char.ccc = uint8(p.Uint(ucd.CanonicalCombiningClass)) - decmap := p.String(ucd.DecompMapping) - - exp, err := parseDecomposition(decmap, false) - isCompat := false - if err != nil { - if len(decmap) > 0 { - exp, err = parseDecomposition(decmap, true) - if err != nil { - log.Fatalf(`%U: bad decomp |%v|: "%s"`, r, decmap, err) - } - isCompat = true - } - } - - char.name = p.String(ucd.Name) - char.codePoint = r - char.forms[FCompatibility].decomp = exp - if !isCompat { - char.forms[FCanonical].decomp = exp - } else { - char.compatDecomp = true - } - if len(decmap) > 0 { - char.forms[FCompatibility].decomp = exp - } - } - if err := p.Err(); err != nil { - log.Fatal(err) - } -} - -// compactCCC converts the sparse set of CCC values to a continguous one, -// reducing the number of bits needed from 8 to 6. -func compactCCC() { - m := make(map[uint8]uint8) - for i := range chars { - c := &chars[i] - m[c.ccc] = 0 - } - cccs := []int{} - for v, _ := range m { - cccs = append(cccs, int(v)) - } - sort.Ints(cccs) - for i, c := range cccs { - cccMap[uint8(i)] = uint8(c) - m[uint8(c)] = uint8(i) - } - for i := range chars { - c := &chars[i] - c.origCCC = c.ccc - c.ccc = m[c.ccc] - } - if len(m) >= 1<<6 { - log.Fatalf("too many difference CCC values: %d >= 64", len(m)) - } -} - -// CompositionExclusions.txt has form: -// 0958 # ... -// See https://unicode.org/reports/tr44/ for full explanation -func loadCompositionExclusions() { - f := gen.OpenUCDFile("CompositionExclusions.txt") - defer f.Close() - p := ucd.New(f) - for p.Next() { - c := &chars[p.Rune(0)] - if c.excludeInComp { - log.Fatalf("%U: Duplicate entry in exclusions.", c.codePoint) - } - c.excludeInComp = true - } - if e := p.Err(); e != nil { - log.Fatal(e) - } -} - -// hasCompatDecomp returns true if any of the recursive -// decompositions contains a compatibility expansion. -// In this case, the character may not occur in NFK*. -func hasCompatDecomp(r rune) bool { - c := &chars[r] - if c.compatDecomp { - return true - } - for _, d := range c.forms[FCompatibility].decomp { - if hasCompatDecomp(d) { - return true - } - } - return false -} - -// Hangul related constants. -const ( - HangulBase = 0xAC00 - HangulEnd = 0xD7A4 // hangulBase + Jamo combinations (19 * 21 * 28) - - JamoLBase = 0x1100 - JamoLEnd = 0x1113 - JamoVBase = 0x1161 - JamoVEnd = 0x1176 - JamoTBase = 0x11A8 - JamoTEnd = 0x11C3 - - JamoLVTCount = 19 * 21 * 28 - JamoTCount = 28 -) - -func isHangul(r rune) bool { - return HangulBase <= r && r < HangulEnd -} - -func isHangulWithoutJamoT(r rune) bool { - if !isHangul(r) { - return false - } - r -= HangulBase - return r < JamoLVTCount && r%JamoTCount == 0 -} - -func ccc(r rune) uint8 { - return chars[r].ccc -} - -// Insert a rune in a buffer, ordered by Canonical Combining Class. -func insertOrdered(b Decomposition, r rune) Decomposition { - n := len(b) - b = append(b, 0) - cc := ccc(r) - if cc > 0 { - // Use bubble sort. - for ; n > 0; n-- { - if ccc(b[n-1]) <= cc { - break - } - b[n] = b[n-1] - } - } - b[n] = r - return b -} - -// Recursively decompose. -func decomposeRecursive(form int, r rune, d Decomposition) Decomposition { - dcomp := chars[r].forms[form].decomp - if len(dcomp) == 0 { - return insertOrdered(d, r) - } - for _, c := range dcomp { - d = decomposeRecursive(form, c, d) - } - return d -} - -func completeCharFields(form int) { - // Phase 0: pre-expand decomposition. - for i := range chars { - f := &chars[i].forms[form] - if len(f.decomp) == 0 { - continue - } - exp := make(Decomposition, 0) - for _, c := range f.decomp { - exp = decomposeRecursive(form, c, exp) - } - f.expandedDecomp = exp - } - - // Phase 1: composition exclusion, mark decomposition. - for i := range chars { - c := &chars[i] - f := &c.forms[form] - - // Marks script-specific exclusions and version restricted. - f.isOneWay = c.excludeInComp - - // Singletons - f.isOneWay = f.isOneWay || len(f.decomp) == 1 - - // Non-starter decompositions - if len(f.decomp) > 1 { - chk := c.ccc != 0 || chars[f.decomp[0]].ccc != 0 - f.isOneWay = f.isOneWay || chk - } - - // Runes that decompose into more than two runes. - f.isOneWay = f.isOneWay || len(f.decomp) > 2 - - if form == FCompatibility { - f.isOneWay = f.isOneWay || hasCompatDecomp(c.codePoint) - } - - for _, r := range f.decomp { - chars[r].forms[form].inDecomp = true - } - } - - // Phase 2: forward and backward combining. - for i := range chars { - c := &chars[i] - f := &c.forms[form] - - if !f.isOneWay && len(f.decomp) == 2 { - f0 := &chars[f.decomp[0]].forms[form] - f1 := &chars[f.decomp[1]].forms[form] - if !f0.isOneWay { - f0.combinesForward = true - } - if !f1.isOneWay { - f1.combinesBackward = true - } - } - if isHangulWithoutJamoT(rune(i)) { - f.combinesForward = true - } - } - - // Phase 3: quick check values. - for i := range chars { - c := &chars[i] - f := &c.forms[form] - - switch { - case len(f.decomp) > 0: - f.quickCheck[MDecomposed] = QCNo - case isHangul(rune(i)): - f.quickCheck[MDecomposed] = QCNo - default: - f.quickCheck[MDecomposed] = QCYes - } - switch { - case f.isOneWay: - f.quickCheck[MComposed] = QCNo - case (i & 0xffff00) == JamoLBase: - f.quickCheck[MComposed] = QCYes - if JamoLBase <= i && i < JamoLEnd { - f.combinesForward = true - } - if JamoVBase <= i && i < JamoVEnd { - f.quickCheck[MComposed] = QCMaybe - f.combinesBackward = true - f.combinesForward = true - } - if JamoTBase <= i && i < JamoTEnd { - f.quickCheck[MComposed] = QCMaybe - f.combinesBackward = true - } - case !f.combinesBackward: - f.quickCheck[MComposed] = QCYes - default: - f.quickCheck[MComposed] = QCMaybe - } - } -} - -func computeNonStarterCounts() { - // Phase 4: leading and trailing non-starter count - for i := range chars { - c := &chars[i] - - runes := []rune{rune(i)} - // We always use FCompatibility so that the CGJ insertion points do not - // change for repeated normalizations with different forms. - if exp := c.forms[FCompatibility].expandedDecomp; len(exp) > 0 { - runes = exp - } - // We consider runes that combine backwards to be non-starters for the - // purpose of Stream-Safe Text Processing. - for _, r := range runes { - if cr := &chars[r]; cr.ccc == 0 && !cr.forms[FCompatibility].combinesBackward { - break - } - c.nLeadingNonStarters++ - } - for i := len(runes) - 1; i >= 0; i-- { - if cr := &chars[runes[i]]; cr.ccc == 0 && !cr.forms[FCompatibility].combinesBackward { - break - } - c.nTrailingNonStarters++ - } - if c.nTrailingNonStarters > 3 { - log.Fatalf("%U: Decomposition with more than 3 (%d) trailing modifiers (%U)", i, c.nTrailingNonStarters, runes) - } - - if isHangul(rune(i)) { - c.nTrailingNonStarters = 2 - if isHangulWithoutJamoT(rune(i)) { - c.nTrailingNonStarters = 1 - } - } - - if l, t := c.nLeadingNonStarters, c.nTrailingNonStarters; l > 0 && l != t { - log.Fatalf("%U: number of leading and trailing non-starters should be equal (%d vs %d)", i, l, t) - } - if t := c.nTrailingNonStarters; t > 3 { - log.Fatalf("%U: number of trailing non-starters is %d > 3", t) - } - } -} - -func printBytes(w io.Writer, b []byte, name string) { - fmt.Fprintf(w, "// %s: %d bytes\n", name, len(b)) - fmt.Fprintf(w, "var %s = [...]byte {", name) - for i, c := range b { - switch { - case i%64 == 0: - fmt.Fprintf(w, "\n// Bytes %x - %x\n", i, i+63) - case i%8 == 0: - fmt.Fprintf(w, "\n") - } - fmt.Fprintf(w, "0x%.2X, ", c) - } - fmt.Fprint(w, "\n}\n\n") -} - -// See forminfo.go for format. -func makeEntry(f *FormInfo, c *Char) uint16 { - e := uint16(0) - if r := c.codePoint; HangulBase <= r && r < HangulEnd { - e |= 0x40 - } - if f.combinesForward { - e |= 0x20 - } - if f.quickCheck[MDecomposed] == QCNo { - e |= 0x4 - } - switch f.quickCheck[MComposed] { - case QCYes: - case QCNo: - e |= 0x10 - case QCMaybe: - e |= 0x18 - default: - log.Fatalf("Illegal quickcheck value %v.", f.quickCheck[MComposed]) - } - e |= uint16(c.nTrailingNonStarters) - return e -} - -// decompSet keeps track of unique decompositions, grouped by whether -// the decomposition is followed by a trailing and/or leading CCC. -type decompSet [7]map[string]bool - -const ( - normalDecomp = iota - firstMulti - firstCCC - endMulti - firstLeadingCCC - firstCCCZeroExcept - firstStarterWithNLead - lastDecomp -) - -var cname = []string{"firstMulti", "firstCCC", "endMulti", "firstLeadingCCC", "firstCCCZeroExcept", "firstStarterWithNLead", "lastDecomp"} - -func makeDecompSet() decompSet { - m := decompSet{} - for i := range m { - m[i] = make(map[string]bool) - } - return m -} -func (m *decompSet) insert(key int, s string) { - m[key][s] = true -} - -func printCharInfoTables(w io.Writer) int { - mkstr := func(r rune, f *FormInfo) (int, string) { - d := f.expandedDecomp - s := string([]rune(d)) - if max := 1 << 6; len(s) >= max { - const msg = "%U: too many bytes in decomposition: %d >= %d" - log.Fatalf(msg, r, len(s), max) - } - head := uint8(len(s)) - if f.quickCheck[MComposed] != QCYes { - head |= 0x40 - } - if f.combinesForward { - head |= 0x80 - } - s = string([]byte{head}) + s - - lccc := ccc(d[0]) - tccc := ccc(d[len(d)-1]) - cc := ccc(r) - if cc != 0 && lccc == 0 && tccc == 0 { - log.Fatalf("%U: trailing and leading ccc are 0 for non-zero ccc %d", r, cc) - } - if tccc < lccc && lccc != 0 { - const msg = "%U: lccc (%d) must be <= tcc (%d)" - log.Fatalf(msg, r, lccc, tccc) - } - index := normalDecomp - nTrail := chars[r].nTrailingNonStarters - nLead := chars[r].nLeadingNonStarters - if tccc > 0 || lccc > 0 || nTrail > 0 { - tccc <<= 2 - tccc |= nTrail - s += string([]byte{tccc}) - index = endMulti - for _, r := range d[1:] { - if ccc(r) == 0 { - index = firstCCC - } - } - if lccc > 0 || nLead > 0 { - s += string([]byte{lccc}) - if index == firstCCC { - log.Fatalf("%U: multi-segment decomposition not supported for decompositions with leading CCC != 0", r) - } - index = firstLeadingCCC - } - if cc != lccc { - if cc != 0 { - log.Fatalf("%U: for lccc != ccc, expected ccc to be 0; was %d", r, cc) - } - index = firstCCCZeroExcept - } - } else if len(d) > 1 { - index = firstMulti - } - return index, s - } - - decompSet := makeDecompSet() - const nLeadStr = "\x00\x01" // 0-byte length and tccc with nTrail. - decompSet.insert(firstStarterWithNLead, nLeadStr) - - // Store the uniqued decompositions in a byte buffer, - // preceded by their byte length. - for _, c := range chars { - for _, f := range c.forms { - if len(f.expandedDecomp) == 0 { - continue - } - if f.combinesBackward { - log.Fatalf("%U: combinesBackward and decompose", c.codePoint) - } - index, s := mkstr(c.codePoint, &f) - decompSet.insert(index, s) - } - } - - decompositions := bytes.NewBuffer(make([]byte, 0, 10000)) - size := 0 - positionMap := make(map[string]uint16) - decompositions.WriteString("\000") - fmt.Fprintln(w, "const (") - for i, m := range decompSet { - sa := []string{} - for s := range m { - sa = append(sa, s) - } - sort.Strings(sa) - for _, s := range sa { - p := decompositions.Len() - decompositions.WriteString(s) - positionMap[s] = uint16(p) - } - if cname[i] != "" { - fmt.Fprintf(w, "%s = 0x%X\n", cname[i], decompositions.Len()) - } - } - fmt.Fprintln(w, "maxDecomp = 0x8000") - fmt.Fprintln(w, ")") - b := decompositions.Bytes() - printBytes(w, b, "decomps") - size += len(b) - - varnames := []string{"nfc", "nfkc"} - for i := 0; i < FNumberOfFormTypes; i++ { - trie := triegen.NewTrie(varnames[i]) - - for r, c := range chars { - f := c.forms[i] - d := f.expandedDecomp - if len(d) != 0 { - _, key := mkstr(c.codePoint, &f) - trie.Insert(rune(r), uint64(positionMap[key])) - if c.ccc != ccc(d[0]) { - // We assume the lead ccc of a decomposition !=0 in this case. - if ccc(d[0]) == 0 { - log.Fatalf("Expected leading CCC to be non-zero; ccc is %d", c.ccc) - } - } - } else if c.nLeadingNonStarters > 0 && len(f.expandedDecomp) == 0 && c.ccc == 0 && !f.combinesBackward { - // Handle cases where it can't be detected that the nLead should be equal - // to nTrail. - trie.Insert(c.codePoint, uint64(positionMap[nLeadStr])) - } else if v := makeEntry(&f, &c)<<8 | uint16(c.ccc); v != 0 { - trie.Insert(c.codePoint, uint64(0x8000|v)) - } - } - sz, err := trie.Gen(w, triegen.Compact(&normCompacter{name: varnames[i]})) - if err != nil { - log.Fatal(err) - } - size += sz - } - return size -} - -func contains(sa []string, s string) bool { - for _, a := range sa { - if a == s { - return true - } - } - return false -} - -func makeTables() { - w := &bytes.Buffer{} - - size := 0 - if *tablelist == "" { - return - } - list := strings.Split(*tablelist, ",") - if *tablelist == "all" { - list = []string{"recomp", "info"} - } - - // Compute maximum decomposition size. - max := 0 - for _, c := range chars { - if n := len(string(c.forms[FCompatibility].expandedDecomp)); n > max { - max = n - } - } - fmt.Fprintln(w, `import "sync"`) - fmt.Fprintln(w) - - fmt.Fprintln(w, "const (") - fmt.Fprintln(w, "\t// Version is the Unicode edition from which the tables are derived.") - fmt.Fprintf(w, "\tVersion = %q\n", gen.UnicodeVersion()) - fmt.Fprintln(w) - fmt.Fprintln(w, "\t// MaxTransformChunkSize indicates the maximum number of bytes that Transform") - fmt.Fprintln(w, "\t// may need to write atomically for any Form. Making a destination buffer at") - fmt.Fprintln(w, "\t// least this size ensures that Transform can always make progress and that") - fmt.Fprintln(w, "\t// the user does not need to grow the buffer on an ErrShortDst.") - fmt.Fprintf(w, "\tMaxTransformChunkSize = %d+maxNonStarters*4\n", len(string(0x034F))+max) - fmt.Fprintln(w, ")\n") - - // Print the CCC remap table. - size += len(cccMap) - fmt.Fprintf(w, "var ccc = [%d]uint8{", len(cccMap)) - for i := 0; i < len(cccMap); i++ { - if i%8 == 0 { - fmt.Fprintln(w) - } - fmt.Fprintf(w, "%3d, ", cccMap[uint8(i)]) - } - fmt.Fprintln(w, "\n}\n") - - if contains(list, "info") { - size += printCharInfoTables(w) - } - - if contains(list, "recomp") { - // Note that we use 32 bit keys, instead of 64 bit. - // This clips the bits of three entries, but we know - // this won't cause a collision. The compiler will catch - // any changes made to UnicodeData.txt that introduces - // a collision. - // Note that the recomposition map for NFC and NFKC - // are identical. - - // Recomposition map - nrentries := 0 - for _, c := range chars { - f := c.forms[FCanonical] - if !f.isOneWay && len(f.decomp) > 0 { - nrentries++ - } - } - sz := nrentries * 8 - size += sz - fmt.Fprintf(w, "// recompMap: %d bytes (entries only)\n", sz) - fmt.Fprintln(w, "var recompMap map[uint32]rune") - fmt.Fprintln(w, "var recompMapOnce sync.Once\n") - fmt.Fprintln(w, `const recompMapPacked = "" +`) - var buf [8]byte - for i, c := range chars { - f := c.forms[FCanonical] - d := f.decomp - if !f.isOneWay && len(d) > 0 { - key := uint32(uint16(d[0]))<<16 + uint32(uint16(d[1])) - binary.BigEndian.PutUint32(buf[:4], key) - binary.BigEndian.PutUint32(buf[4:], uint32(i)) - fmt.Fprintf(w, "\t\t%q + // 0x%.8X: 0x%.8X\n", string(buf[:]), key, uint32(i)) - } - } - // hack so we don't have to special case the trailing plus sign - fmt.Fprintf(w, ` ""`) - fmt.Fprintln(w) - } - - fmt.Fprintf(w, "// Total size of tables: %dKB (%d bytes)\n", (size+512)/1024, size) - gen.WriteVersionedGoFile("tables.go", "norm", w.Bytes()) -} - -func printChars() { - if *verbose { - for _, c := range chars { - if !c.isValid() || c.state == SMissing { - continue - } - fmt.Println(c) - } - } -} - -// verifyComputed does various consistency tests. -func verifyComputed() { - for i, c := range chars { - for _, f := range c.forms { - isNo := (f.quickCheck[MDecomposed] == QCNo) - if (len(f.decomp) > 0) != isNo && !isHangul(rune(i)) { - log.Fatalf("%U: NF*D QC must be No if rune decomposes", i) - } - - isMaybe := f.quickCheck[MComposed] == QCMaybe - if f.combinesBackward != isMaybe { - log.Fatalf("%U: NF*C QC must be Maybe if combinesBackward", i) - } - if len(f.decomp) > 0 && f.combinesForward && isMaybe { - log.Fatalf("%U: NF*C QC must be Yes or No if combinesForward and decomposes", i) - } - - if len(f.expandedDecomp) != 0 { - continue - } - if a, b := c.nLeadingNonStarters > 0, (c.ccc > 0 || f.combinesBackward); a != b { - // We accept these runes to be treated differently (it only affects - // segment breaking in iteration, most likely on improper use), but - // reconsider if more characters are added. - // U+FF9E HALFWIDTH KATAKANA VOICED SOUND MARK;Lm;0;L; 3099;;;;N;;;;; - // U+FF9F HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK;Lm;0;L; 309A;;;;N;;;;; - // U+3133 HANGUL LETTER KIYEOK-SIOS;Lo;0;L; 11AA;;;;N;HANGUL LETTER GIYEOG SIOS;;;; - // U+318E HANGUL LETTER ARAEAE;Lo;0;L; 11A1;;;;N;HANGUL LETTER ALAE AE;;;; - // U+FFA3 HALFWIDTH HANGUL LETTER KIYEOK-SIOS;Lo;0;L; 3133;;;;N;HALFWIDTH HANGUL LETTER GIYEOG SIOS;;;; - // U+FFDC HALFWIDTH HANGUL LETTER I;Lo;0;L; 3163;;;;N;;;;; - if i != 0xFF9E && i != 0xFF9F && !(0x3133 <= i && i <= 0x318E) && !(0xFFA3 <= i && i <= 0xFFDC) { - log.Fatalf("%U: nLead was %v; want %v", i, a, b) - } - } - } - nfc := c.forms[FCanonical] - nfkc := c.forms[FCompatibility] - if nfc.combinesBackward != nfkc.combinesBackward { - log.Fatalf("%U: Cannot combine combinesBackward\n", c.codePoint) - } - } -} - -// Use values in DerivedNormalizationProps.txt to compare against the -// values we computed. -// DerivedNormalizationProps.txt has form: -// 00C0..00C5 ; NFD_QC; N # ... -// 0374 ; NFD_QC; N # ... -// See https://unicode.org/reports/tr44/ for full explanation -func testDerived() { - f := gen.OpenUCDFile("DerivedNormalizationProps.txt") - defer f.Close() - p := ucd.New(f) - for p.Next() { - r := p.Rune(0) - c := &chars[r] - - var ftype, mode int - qt := p.String(1) - switch qt { - case "NFC_QC": - ftype, mode = FCanonical, MComposed - case "NFD_QC": - ftype, mode = FCanonical, MDecomposed - case "NFKC_QC": - ftype, mode = FCompatibility, MComposed - case "NFKD_QC": - ftype, mode = FCompatibility, MDecomposed - default: - continue - } - var qr QCResult - switch p.String(2) { - case "Y": - qr = QCYes - case "N": - qr = QCNo - case "M": - qr = QCMaybe - default: - log.Fatalf(`Unexpected quick check value "%s"`, p.String(2)) - } - if got := c.forms[ftype].quickCheck[mode]; got != qr { - log.Printf("%U: FAILED %s (was %v need %v)\n", r, qt, got, qr) - } - c.forms[ftype].verified[mode] = true - } - if err := p.Err(); err != nil { - log.Fatal(err) - } - // Any unspecified value must be QCYes. Verify this. - for i, c := range chars { - for j, fd := range c.forms { - for k, qr := range fd.quickCheck { - if !fd.verified[k] && qr != QCYes { - m := "%U: FAIL F:%d M:%d (was %v need Yes) %s\n" - log.Printf(m, i, j, k, qr, c.name) - } - } - } - } -} - -var testHeader = `const ( - Yes = iota - No - Maybe -) - -type formData struct { - qc uint8 - combinesForward bool - decomposition string -} - -type runeData struct { - r rune - ccc uint8 - nLead uint8 - nTrail uint8 - f [2]formData // 0: canonical; 1: compatibility -} - -func f(qc uint8, cf bool, dec string) [2]formData { - return [2]formData{{qc, cf, dec}, {qc, cf, dec}} -} - -func g(qc, qck uint8, cf, cfk bool, d, dk string) [2]formData { - return [2]formData{{qc, cf, d}, {qck, cfk, dk}} -} - -var testData = []runeData{ -` - -func printTestdata() { - type lastInfo struct { - ccc uint8 - nLead uint8 - nTrail uint8 - f string - } - - last := lastInfo{} - w := &bytes.Buffer{} - fmt.Fprintf(w, testHeader) - for r, c := range chars { - f := c.forms[FCanonical] - qc, cf, d := f.quickCheck[MComposed], f.combinesForward, string(f.expandedDecomp) - f = c.forms[FCompatibility] - qck, cfk, dk := f.quickCheck[MComposed], f.combinesForward, string(f.expandedDecomp) - s := "" - if d == dk && qc == qck && cf == cfk { - s = fmt.Sprintf("f(%s, %v, %q)", qc, cf, d) - } else { - s = fmt.Sprintf("g(%s, %s, %v, %v, %q, %q)", qc, qck, cf, cfk, d, dk) - } - current := lastInfo{c.ccc, c.nLeadingNonStarters, c.nTrailingNonStarters, s} - if last != current { - fmt.Fprintf(w, "\t{0x%x, %d, %d, %d, %s},\n", r, c.origCCC, c.nLeadingNonStarters, c.nTrailingNonStarters, s) - last = current - } - } - fmt.Fprintln(w, "}") - gen.WriteVersionedGoFile("data_test.go", "norm", w.Bytes()) -} diff --git a/vendor/golang.org/x/text/unicode/norm/triegen.go b/vendor/golang.org/x/text/unicode/norm/triegen.go deleted file mode 100644 index 45d71190..00000000 --- a/vendor/golang.org/x/text/unicode/norm/triegen.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// Trie table generator. -// Used by make*tables tools to generate a go file with trie data structures -// for mapping UTF-8 to a 16-bit value. All but the last byte in a UTF-8 byte -// sequence are used to lookup offsets in the index table to be used for the -// next byte. The last byte is used to index into a table with 16-bit values. - -package main - -import ( - "fmt" - "io" -) - -const maxSparseEntries = 16 - -type normCompacter struct { - sparseBlocks [][]uint64 - sparseOffset []uint16 - sparseCount int - name string -} - -func mostFrequentStride(a []uint64) int { - counts := make(map[int]int) - var v int - for _, x := range a { - if stride := int(x) - v; v != 0 && stride >= 0 { - counts[stride]++ - } - v = int(x) - } - var maxs, maxc int - for stride, cnt := range counts { - if cnt > maxc || (cnt == maxc && stride < maxs) { - maxs, maxc = stride, cnt - } - } - return maxs -} - -func countSparseEntries(a []uint64) int { - stride := mostFrequentStride(a) - var v, count int - for _, tv := range a { - if int(tv)-v != stride { - if tv != 0 { - count++ - } - } - v = int(tv) - } - return count -} - -func (c *normCompacter) Size(v []uint64) (sz int, ok bool) { - if n := countSparseEntries(v); n <= maxSparseEntries { - return (n+1)*4 + 2, true - } - return 0, false -} - -func (c *normCompacter) Store(v []uint64) uint32 { - h := uint32(len(c.sparseOffset)) - c.sparseBlocks = append(c.sparseBlocks, v) - c.sparseOffset = append(c.sparseOffset, uint16(c.sparseCount)) - c.sparseCount += countSparseEntries(v) + 1 - return h -} - -func (c *normCompacter) Handler() string { - return c.name + "Sparse.lookup" -} - -func (c *normCompacter) Print(w io.Writer) (retErr error) { - p := func(f string, x ...interface{}) { - if _, err := fmt.Fprintf(w, f, x...); retErr == nil && err != nil { - retErr = err - } - } - - ls := len(c.sparseBlocks) - p("// %sSparseOffset: %d entries, %d bytes\n", c.name, ls, ls*2) - p("var %sSparseOffset = %#v\n\n", c.name, c.sparseOffset) - - ns := c.sparseCount - p("// %sSparseValues: %d entries, %d bytes\n", c.name, ns, ns*4) - p("var %sSparseValues = [%d]valueRange {", c.name, ns) - for i, b := range c.sparseBlocks { - p("\n// Block %#x, offset %#x", i, c.sparseOffset[i]) - var v int - stride := mostFrequentStride(b) - n := countSparseEntries(b) - p("\n{value:%#04x,lo:%#02x},", stride, uint8(n)) - for i, nv := range b { - if int(nv)-v != stride { - if v != 0 { - p(",hi:%#02x},", 0x80+i-1) - } - if nv != 0 { - p("\n{value:%#04x,lo:%#02x", nv, 0x80+i) - } - } - v = int(nv) - } - if v != 0 { - p(",hi:%#02x},", 0x80+len(b)-1) - } - } - p("\n}\n\n") - return -} diff --git a/vendor/golang.org/x/tools/go/gcexportdata/main.go b/vendor/golang.org/x/tools/go/gcexportdata/main.go deleted file mode 100644 index 2713dce6..00000000 --- a/vendor/golang.org/x/tools/go/gcexportdata/main.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// The gcexportdata command is a diagnostic tool that displays the -// contents of gc export data files. -package main - -import ( - "flag" - "fmt" - "go/token" - "go/types" - "log" - "os" - - "golang.org/x/tools/go/gcexportdata" - "golang.org/x/tools/go/types/typeutil" -) - -var packageFlag = flag.String("package", "", "alternative package to print") - -func main() { - log.SetPrefix("gcexportdata: ") - log.SetFlags(0) - flag.Usage = func() { - fmt.Fprintln(os.Stderr, "usage: gcexportdata [-package path] file.a") - } - flag.Parse() - if flag.NArg() != 1 { - flag.Usage() - os.Exit(2) - } - filename := flag.Args()[0] - - f, err := os.Open(filename) - if err != nil { - log.Fatal(err) - } - - r, err := gcexportdata.NewReader(f) - if err != nil { - log.Fatalf("%s: %s", filename, err) - } - - // Decode the package. - const primary = "" - imports := make(map[string]*types.Package) - fset := token.NewFileSet() - pkg, err := gcexportdata.Read(r, fset, imports, primary) - if err != nil { - log.Fatalf("%s: %s", filename, err) - } - - // Optionally select an indirectly mentioned package. - if *packageFlag != "" { - pkg = imports[*packageFlag] - if pkg == nil { - fmt.Fprintf(os.Stderr, "export data file %s does not mention %s; has:\n", - filename, *packageFlag) - for p := range imports { - if p != primary { - fmt.Fprintf(os.Stderr, "\t%s\n", p) - } - } - os.Exit(1) - } - } - - // Print all package-level declarations, including non-exported ones. - fmt.Printf("package %s\n", pkg.Name()) - for _, imp := range pkg.Imports() { - fmt.Printf("import %q\n", imp.Path()) - } - qual := func(p *types.Package) string { - if pkg == p { - return "" - } - return p.Name() - } - scope := pkg.Scope() - for _, name := range scope.Names() { - obj := scope.Lookup(name) - fmt.Printf("%s: %s\n", - fset.Position(obj.Pos()), - types.ObjectString(obj, qual)) - - // For types, print each method. - if _, ok := obj.(*types.TypeName); ok { - for _, method := range typeutil.IntuitiveMethodSet(obj.Type(), nil) { - fmt.Printf("%s: %s\n", - fset.Position(method.Obj().Pos()), - types.SelectionString(method, qual)) - } - } - } -} diff --git a/vendor/modules.txt b/vendor/modules.txt index ff52620c..c241a184 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -5,15 +5,15 @@ github.com/beevik/etree # github.com/beorn7/perks v1.0.0 github.com/beorn7/perks/quantile # github.com/coreos/etcd v3.3.13+incompatible +github.com/coreos/etcd/auth/authpb github.com/coreos/etcd/clientv3 github.com/coreos/etcd/clientv3/namespace -github.com/coreos/etcd/pkg/transport -github.com/coreos/etcd/auth/authpb github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes github.com/coreos/etcd/etcdserver/etcdserverpb github.com/coreos/etcd/mvcc/mvccpb -github.com/coreos/etcd/pkg/types github.com/coreos/etcd/pkg/tlsutil +github.com/coreos/etcd/pkg/transport +github.com/coreos/etcd/pkg/types # github.com/coreos/go-oidc v2.0.0+incompatible github.com/coreos/go-oidc # github.com/davecgh/go-spew v1.1.1 @@ -29,14 +29,14 @@ github.com/gogo/protobuf/gogoproto github.com/gogo/protobuf/proto github.com/gogo/protobuf/protoc-gen-gogo/descriptor # github.com/golang/protobuf v1.3.2 -github.com/golang/protobuf/protoc-gen-go github.com/golang/protobuf/proto -github.com/golang/protobuf/protoc-gen-go/generator -github.com/golang/protobuf/protoc-gen-go/grpc -github.com/golang/protobuf/ptypes +github.com/golang/protobuf/protoc-gen-go github.com/golang/protobuf/protoc-gen-go/descriptor +github.com/golang/protobuf/protoc-gen-go/generator github.com/golang/protobuf/protoc-gen-go/generator/internal/remap +github.com/golang/protobuf/protoc-gen-go/grpc github.com/golang/protobuf/protoc-gen-go/plugin +github.com/golang/protobuf/ptypes github.com/golang/protobuf/ptypes/any github.com/golang/protobuf/ptypes/duration github.com/golang/protobuf/ptypes/timestamp @@ -59,8 +59,8 @@ github.com/jonboulle/clockwork # github.com/konsorten/go-windows-terminal-sequences v1.0.2 github.com/konsorten/go-windows-terminal-sequences # github.com/kylelemons/godebug v1.1.0 -github.com/kylelemons/godebug/pretty github.com/kylelemons/godebug/diff +github.com/kylelemons/godebug/pretty # github.com/lib/pq v1.2.0 github.com/lib/pq github.com/lib/pq/oid @@ -76,14 +76,14 @@ github.com/pquerna/cachecontrol github.com/pquerna/cachecontrol/cacheobject # github.com/prometheus/client_golang v1.0.0 github.com/prometheus/client_golang/prometheus -github.com/prometheus/client_golang/prometheus/promhttp github.com/prometheus/client_golang/prometheus/internal +github.com/prometheus/client_golang/prometheus/promhttp # github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90 github.com/prometheus/client_model/go # github.com/prometheus/common v0.6.0 github.com/prometheus/common/expfmt -github.com/prometheus/common/model github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg +github.com/prometheus/common/model # github.com/prometheus/procfs v0.0.3 github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs @@ -100,40 +100,40 @@ github.com/spf13/pflag # github.com/stretchr/testify v1.3.0 github.com/stretchr/testify/assert # go.opencensus.io v0.21.0 +go.opencensus.io +go.opencensus.io/internal +go.opencensus.io/internal/tagencoding +go.opencensus.io/metric/metricdata +go.opencensus.io/metric/metricproducer go.opencensus.io/plugin/ochttp go.opencensus.io/plugin/ochttp/propagation/b3 +go.opencensus.io/resource go.opencensus.io/stats +go.opencensus.io/stats/internal go.opencensus.io/stats/view go.opencensus.io/tag go.opencensus.io/trace -go.opencensus.io/trace/propagation -go.opencensus.io/metric/metricdata -go.opencensus.io/stats/internal -go.opencensus.io/internal/tagencoding -go.opencensus.io/metric/metricproducer -go.opencensus.io/internal go.opencensus.io/trace/internal +go.opencensus.io/trace/propagation go.opencensus.io/trace/tracestate -go.opencensus.io/resource -go.opencensus.io # golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 golang.org/x/crypto/bcrypt golang.org/x/crypto/blowfish golang.org/x/crypto/ed25519 -golang.org/x/crypto/pbkdf2 golang.org/x/crypto/ed25519/internal/edwards25519 +golang.org/x/crypto/pbkdf2 # golang.org/x/lint v0.0.0-20190409202823-959b441ac422 -golang.org/x/lint/golint golang.org/x/lint +golang.org/x/lint/golint # golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7 -golang.org/x/net/http2 -golang.org/x/net/trace golang.org/x/net/context +golang.org/x/net/context/ctxhttp golang.org/x/net/http/httpguts +golang.org/x/net/http2 golang.org/x/net/http2/hpack golang.org/x/net/idna golang.org/x/net/internal/timeseries -golang.org/x/net/context/ctxhttp +golang.org/x/net/trace # golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 golang.org/x/oauth2 golang.org/x/oauth2/bitbucket @@ -143,13 +143,13 @@ golang.org/x/oauth2/internal golang.org/x/oauth2/jws golang.org/x/oauth2/jwt # golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a -golang.org/x/sys/windows golang.org/x/sys/unix +golang.org/x/sys/windows # golang.org/x/text v0.3.2 golang.org/x/text/secure/bidirule +golang.org/x/text/transform golang.org/x/text/unicode/bidi golang.org/x/text/unicode/norm -golang.org/x/text/transform # golang.org/x/tools v0.0.0-20190813214729-9dba7caff850 golang.org/x/tools/go/ast/astutil golang.org/x/tools/go/gcexportdata @@ -158,38 +158,40 @@ golang.org/x/tools/go/internal/gcimporter google.golang.org/api/admin/directory/v1 google.golang.org/api/gensupport google.golang.org/api/googleapi +google.golang.org/api/googleapi/internal/uritemplates +google.golang.org/api/googleapi/transport +google.golang.org/api/internal google.golang.org/api/option google.golang.org/api/transport/http -google.golang.org/api/googleapi/internal/uritemplates -google.golang.org/api/internal -google.golang.org/api/googleapi/transport google.golang.org/api/transport/http/internal/propagation # google.golang.org/appengine v1.6.1 google.golang.org/appengine google.golang.org/appengine/cloudsql -google.golang.org/appengine/urlfetch google.golang.org/appengine/internal google.golang.org/appengine/internal/app_identity -google.golang.org/appengine/internal/modules -google.golang.org/appengine/internal/urlfetch google.golang.org/appengine/internal/base google.golang.org/appengine/internal/datastore google.golang.org/appengine/internal/log +google.golang.org/appengine/internal/modules google.golang.org/appengine/internal/remote_api +google.golang.org/appengine/internal/urlfetch +google.golang.org/appengine/urlfetch # google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64 google.golang.org/genproto/googleapis/rpc/status # google.golang.org/grpc v1.23.0 google.golang.org/grpc -google.golang.org/grpc/codes -google.golang.org/grpc/status -google.golang.org/grpc/credentials -google.golang.org/grpc/reflection google.golang.org/grpc/balancer +google.golang.org/grpc/balancer/base google.golang.org/grpc/balancer/roundrobin +google.golang.org/grpc/binarylog/grpc_binarylog_v1 +google.golang.org/grpc/codes google.golang.org/grpc/connectivity +google.golang.org/grpc/credentials +google.golang.org/grpc/credentials/internal google.golang.org/grpc/encoding google.golang.org/grpc/encoding/proto google.golang.org/grpc/grpclog +google.golang.org/grpc/health/grpc_health_v1 google.golang.org/grpc/internal google.golang.org/grpc/internal/backoff google.golang.org/grpc/internal/balancerload @@ -198,23 +200,21 @@ google.golang.org/grpc/internal/channelz google.golang.org/grpc/internal/envconfig google.golang.org/grpc/internal/grpcrand google.golang.org/grpc/internal/grpcsync +google.golang.org/grpc/internal/syscall google.golang.org/grpc/internal/transport google.golang.org/grpc/keepalive google.golang.org/grpc/metadata google.golang.org/grpc/naming google.golang.org/grpc/peer +google.golang.org/grpc/reflection +google.golang.org/grpc/reflection/grpc_reflection_v1alpha google.golang.org/grpc/resolver google.golang.org/grpc/resolver/dns google.golang.org/grpc/resolver/passthrough google.golang.org/grpc/serviceconfig google.golang.org/grpc/stats +google.golang.org/grpc/status google.golang.org/grpc/tap -google.golang.org/grpc/credentials/internal -google.golang.org/grpc/reflection/grpc_reflection_v1alpha -google.golang.org/grpc/health/grpc_health_v1 -google.golang.org/grpc/balancer/base -google.golang.org/grpc/binarylog/grpc_binarylog_v1 -google.golang.org/grpc/internal/syscall # gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d gopkg.in/asn1-ber.v1 # gopkg.in/ldap.v2 v2.5.1 From 0773c6e9f3315b2ba25c0d7ab63c165fc5ac5d15 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Fri, 6 Dec 2019 16:49:30 +0100 Subject: [PATCH 56/72] Add github actions CI flow --- .github/workflows/.editorconfig | 2 + .github/workflows/ci.yml | 77 +++++++++++++++++++++++++++++++++ storage/sql/config_test.go | 25 +++++++++++ storage/sql/postgres_test.go | 13 ++++++ 4 files changed, 117 insertions(+) create mode 100644 .github/workflows/.editorconfig create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/.editorconfig b/.github/workflows/.editorconfig new file mode 100644 index 00000000..7bd3346f --- /dev/null +++ b/.github/workflows/.editorconfig @@ -0,0 +1,2 @@ +[*.yml] +indent_size = 2 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..827b0214 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,77 @@ +name: CI + +on: + push: + branches: + - master + pull_request: + +jobs: + build: + name: Build + runs-on: ubuntu-16.04 + env: + GOFLAGS: -mod=readonly + + services: + postgres: + image: postgres:10.8 + ports: + - 5432 + options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 + + etcd: + image: gcr.io/etcd-development/etcd:v3.2.9 + ports: + - 2379 + env: + ETCD_LISTEN_CLIENT_URLS: http://0.0.0.0:2379 + ETCD_ADVERTISE_CLIENT_URLS: http://0.0.0.0:2379 + options: --health-cmd "ETCDCTL_API=3 etcdctl --endpoints http://localhost:2379 endpoint health" --health-interval 10s --health-timeout 5s --health-retries 5 + + keystone: + image: openio/openstack-keystone:pike + ports: + - 5000 + - 35357 + options: --health-cmd "curl --fail http://localhost:5000/v3" --health-interval 10s --health-timeout 5s --health-retries 5 + + steps: + - name: Set up Go + uses: actions/setup-go@v1 + with: + go-version: 1.13 + + - name: Checkout code + uses: actions/checkout@v1 + + - name: Setup MySQL database + run: mysql -u root -proot -e 'CREATE DATABASE dex;' + + - name: Run tests + run: make testall + env: + DEX_MYSQL_DATABASE: dex + DEX_MYSQL_USER: root + DEX_MYSQL_PASSWORD: root + DEX_MYSQL_HOST: 127.0.0.1 + DEX_MYSQL_PORT: 3306 + DEX_POSTGRES_DATABASE: postgres + DEX_POSTGRES_USER: postgres + DEX_POSTGRES_PASSWORD: postgres + DEX_POSTGRES_HOST: localhost + DEX_POSTGRES_PORT: ${{ job.services.postgres.ports[5432] }} + DEX_ETCD_ENDPOINTS: http://localhost:${{ job.services.etcd.ports[2379] }} + # TODO: enable + DEX_LDAP_TESTS: 0 + DEX_KEYSTONE_URL: http://localhost:${{ job.services.keystone.ports[5000] }} + DEX_KEYSTONE_ADMIN_URL: http://localhost:${{ job.services.keystone.ports[35357] }} + DEX_KEYSTONE_ADMIN_USER: demo + DEX_KEYSTONE_ADMIN_PASS: DEMO_PASS + + #- name: Run Kubernetes tests + # run: ./scripts/test-k8s.sh + + # Ensure proto generation doesn't depend on external packages. + - name: Verify proto + run: make verify-proto diff --git a/storage/sql/config_test.go b/storage/sql/config_test.go index b71b2eef..b3694cc3 100644 --- a/storage/sql/config_test.go +++ b/storage/sql/config_test.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "runtime" + "strconv" "testing" "time" @@ -220,12 +221,24 @@ func TestPostgres(t *testing.T) { if host == "" { t.Skipf("test environment variable %q not set, skipping", testPostgresEnv) } + + port := uint64(5432) + if rawPort := os.Getenv("DEX_POSTGRES_PORT"); rawPort != "" { + var err error + + port, err = strconv.ParseUint(rawPort, 10, 32) + if err != nil { + t.Fatalf("invalid postgres port %q: %s", rawPort, err) + } + } + p := &Postgres{ NetworkDB: NetworkDB{ Database: getenv("DEX_POSTGRES_DATABASE", "postgres"), User: getenv("DEX_POSTGRES_USER", "postgres"), Password: getenv("DEX_POSTGRES_PASSWORD", "postgres"), Host: host, + Port: uint16(port), ConnectionTimeout: 5, }, SSL: SSL{ @@ -242,12 +255,24 @@ func TestMySQL(t *testing.T) { if host == "" { t.Skipf("test environment variable %q not set, skipping", testMySQLEnv) } + + port := uint64(3306) + if rawPort := os.Getenv("DEX_MYSQL_PORT"); rawPort != "" { + var err error + + port, err = strconv.ParseUint(rawPort, 10, 32) + if err != nil { + t.Fatalf("invalid mysql port %q: %s", rawPort, err) + } + } + s := &MySQL{ NetworkDB: NetworkDB{ Database: getenv("DEX_MYSQL_DATABASE", "mysql"), User: getenv("DEX_MYSQL_USER", "mysql"), Password: getenv("DEX_MYSQL_PASSWORD", ""), Host: host, + Port: uint16(port), ConnectionTimeout: 5, }, SSL: SSL{ diff --git a/storage/sql/postgres_test.go b/storage/sql/postgres_test.go index adf91927..8071dc29 100644 --- a/storage/sql/postgres_test.go +++ b/storage/sql/postgres_test.go @@ -4,6 +4,7 @@ package sql import ( "os" + "strconv" "testing" ) @@ -12,12 +13,24 @@ func TestPostgresTunables(t *testing.T) { if host == "" { t.Skipf("test environment variable %q not set, skipping", testPostgresEnv) } + + port := uint64(5432) + if rawPort := os.Getenv("DEX_POSTGRES_PORT"); rawPort != "" { + var err error + + port, err = strconv.ParseUint(rawPort, 10, 32) + if err != nil { + t.Fatalf("invalid postgres port %q: %s", rawPort, err) + } + } + baseCfg := &Postgres{ NetworkDB: NetworkDB{ Database: getenv("DEX_POSTGRES_DATABASE", "postgres"), User: getenv("DEX_POSTGRES_USER", "postgres"), Password: getenv("DEX_POSTGRES_PASSWORD", "postgres"), Host: host, + Port: uint16(port), }, SSL: SSL{ Mode: pgSSLDisable, // Postgres container doesn't support SSL. From 5d2529f0adf91afb8839ff2680fdab17a4aa8136 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Sat, 7 Dec 2019 19:58:51 +0100 Subject: [PATCH 57/72] Enable Kubernetes tests --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 827b0214..c90ef595 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -69,8 +69,8 @@ jobs: DEX_KEYSTONE_ADMIN_USER: demo DEX_KEYSTONE_ADMIN_PASS: DEMO_PASS - #- name: Run Kubernetes tests - # run: ./scripts/test-k8s.sh + - name: Run Kubernetes tests + run: ./scripts/test-k8s.sh # Ensure proto generation doesn't depend on external packages. - name: Verify proto From 532c120ba75b7cf98787467ca501ee5d7615e80f Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Sat, 7 Dec 2019 20:06:26 +0100 Subject: [PATCH 58/72] Use vendored dependencies for CI build --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c90ef595..a127d5b0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,7 @@ jobs: name: Build runs-on: ubuntu-16.04 env: - GOFLAGS: -mod=readonly + GOFLAGS: -mod=vendor services: postgres: From d2095bb2d899217be0d43a401528c20e92968273 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Sun, 8 Dec 2019 20:21:28 +0100 Subject: [PATCH 59/72] Rewrite LDAP tests to use Docker --- connector/ldap/ldap_test.go | 311 +- connector/ldap/testdata/{ => certs}/ca.crt | 0 connector/ldap/testdata/{ => certs}/ca.key | 0 connector/ldap/testdata/certs/dhparam.pem | 8 + .../testdata/{server.crt => certs/ldap.crt} | 0 .../testdata/{server.key => certs/ldap.key} | 0 connector/ldap/testdata/core.schema | 610 ---- connector/ldap/testdata/cosine.schema | 2571 ----------------- connector/ldap/testdata/inetorgperson.schema | 155 - connector/ldap/testdata/misc.schema | 75 - connector/ldap/testdata/nis.schema | 237 -- connector/ldap/testdata/openldap.schema | 54 - go.mod | 6 +- go.sum | 101 +- 14 files changed, 165 insertions(+), 3963 deletions(-) rename connector/ldap/testdata/{ => certs}/ca.crt (100%) rename connector/ldap/testdata/{ => certs}/ca.key (100%) create mode 100644 connector/ldap/testdata/certs/dhparam.pem rename connector/ldap/testdata/{server.crt => certs/ldap.crt} (100%) rename connector/ldap/testdata/{server.key => certs/ldap.key} (100%) delete mode 100644 connector/ldap/testdata/core.schema delete mode 100644 connector/ldap/testdata/cosine.schema delete mode 100644 connector/ldap/testdata/inetorgperson.schema delete mode 100644 connector/ldap/testdata/misc.schema delete mode 100644 connector/ldap/testdata/nis.schema delete mode 100644 connector/ldap/testdata/openldap.schema diff --git a/connector/ldap/ldap_test.go b/connector/ldap/ldap_test.go index fa6b7062..1ed2f878 100644 --- a/connector/ldap/ldap_test.go +++ b/connector/ldap/ldap_test.go @@ -1,20 +1,18 @@ package ldap import ( - "bytes" "context" + "fmt" "io/ioutil" - "net/url" "os" - "os/exec" "path/filepath" - "sync" "testing" - "text/template" "time" "github.com/kylelemons/godebug/pretty" "github.com/sirupsen/logrus" + "github.com/testcontainers/testcontainers-go" + "github.com/testcontainers/testcontainers-go/wait" "github.com/dexidp/dex/connector" ) @@ -50,12 +48,6 @@ type subtest struct { func TestQuery(t *testing.T) { schema := ` -dn: dc=example,dc=org -objectClass: dcObject -objectClass: organization -o: Example Company -dc: example - dn: ou=People,dc=example,dc=org objectClass: organizationalUnit ou: People @@ -125,12 +117,6 @@ userpassword: bar func TestQueryWithEmailSuffix(t *testing.T) { schema := ` -dn: dc=example,dc=org -objectClass: dcObject -objectClass: organization -o: Example Company -dc: example - dn: ou=People,dc=example,dc=org objectClass: organizationalUnit ou: People @@ -187,12 +173,6 @@ userpassword: bar func TestUserFilter(t *testing.T) { schema := ` -dn: dc=example,dc=org -objectClass: dcObject -objectClass: organization -o: Example Company -dc: example - dn: ou=Seattle,dc=example,dc=org objectClass: organizationalUnit ou: Seattle @@ -283,12 +263,6 @@ userpassword: bar func TestGroupQuery(t *testing.T) { schema := ` -dn: dc=example,dc=org -objectClass: dcObject -objectClass: organization -o: Example Company -dc: example - dn: ou=People,dc=example,dc=org objectClass: organizationalUnit ou: People @@ -371,12 +345,6 @@ member: cn=jane,ou=People,dc=example,dc=org func TestGroupsOnUserEntity(t *testing.T) { schema := ` -dn: dc=example,dc=org -objectClass: dcObject -objectClass: organization -o: Example Company -dc: example - dn: ou=People,dc=example,dc=org objectClass: organizationalUnit ou: People @@ -468,12 +436,6 @@ gidNumber: 1002 func TestGroupFilter(t *testing.T) { schema := ` -dn: dc=example,dc=org -objectClass: dcObject -objectClass: organization -o: Example Company -dc: example - dn: ou=People,dc=example,dc=org objectClass: organizationalUnit ou: People @@ -574,12 +536,6 @@ member: cn=jane,ou=People,dc=example,dc=org func TestStartTLS(t *testing.T) { schema := ` -dn: dc=example,dc=org -objectClass: dcObject -objectClass: organization -o: Example Company -dc: example - dn: ou=People,dc=example,dc=org objectClass: organizationalUnit ou: People @@ -617,12 +573,6 @@ userpassword: foo func TestInsecureSkipVerify(t *testing.T) { schema := ` -dn: dc=example,dc=org -objectClass: dcObject -objectClass: organization -o: Example Company -dc: example - dn: ou=People,dc=example,dc=org objectClass: organizationalUnit ou: People @@ -660,12 +610,6 @@ userpassword: foo func TestLDAPS(t *testing.T) { schema := ` -dn: dc=example,dc=org -objectClass: dcObject -objectClass: organization -o: Example Company -dc: example - dn: ou=People,dc=example,dc=org objectClass: organizationalUnit ou: People @@ -729,8 +673,7 @@ func TestUsernamePrompt(t *testing.T) { // runTests runs a set of tests against an LDAP schema. It does this by // setting up an OpenLDAP server and injecting the provided scheme. // -// The tests require the slapd and ldapadd binaries available in the host -// machine's PATH. +// The tests require Docker. // // The DEX_LDAP_TESTS must be set to "1" func runTests(t *testing.T, schema string, connMethod connectionMethod, config *Config, tests []subtest) { @@ -738,12 +681,6 @@ func runTests(t *testing.T, schema string, connMethod connectionMethod, config * t.Skipf("%s not set. Skipping test (run 'export %s=1' to run tests)", envVar, envVar) } - for _, cmd := range []string{"slapd", "ldapadd"} { - if _, err := exec.LookPath(cmd); err != nil { - t.Errorf("%s not available", cmd) - } - } - wd, err := os.Getwd() if err != nil { t.Fatal(err) @@ -755,100 +692,65 @@ func runTests(t *testing.T, schema string, connMethod connectionMethod, config * } defer os.RemoveAll(tempDir) - configBytes := new(bytes.Buffer) - - data := tmplData{ - TempDir: tempDir, - Includes: includes(t, wd), - } - data.TLSCertPath, data.TLSKeyPath = tlsAssets(t, wd) - - if err := slapdConfigTmpl.Execute(configBytes, data); err != nil { + schemaPath := filepath.Join(tempDir, "schema.ldif") + if err := ioutil.WriteFile(schemaPath, []byte(schema), 0777); err != nil { t.Fatal(err) } - configPath := filepath.Join(tempDir, "ldap.conf") - if err := ioutil.WriteFile(configPath, configBytes.Bytes(), 0644); err != nil { - t.Fatal(err) - } - schemaPath := filepath.Join(tempDir, "schema.ldap") - if err := ioutil.WriteFile(schemaPath, []byte(schema), 0644); err != nil { - t.Fatal(err) + req := testcontainers.ContainerRequest{ + Image: "osixia/openldap:1.3.0", + ExposedPorts: []string{"389/tcp", "636/tcp"}, + Cmd: []string{"--copy-service"}, + Env: map[string]string{ + "LDAP_BASE_DN": "dc=example,dc=org", + "LDAP_TLS": "true", + "LDAP_TLS_VERIFY_CLIENT": "try", + }, + BindMounts: map[string]string{ + filepath.Join(wd, "testdata", "certs"): "/container/service/slapd/assets/certs", + schemaPath: "/container/service/slapd/assets/config/bootstrap/ldif/99-schema.ldif", + }, + WaitingFor: wait.ForAll( + wait.ForLog("slapd starting").WithOccurrence(3).WithStartupTimeout(time.Minute), + wait.ForListeningPort("389/tcp"), + wait.ForListeningPort("636/tcp"), + ), } - socketPath := url.QueryEscape(filepath.Join(tempDir, "ldap.unix")) + ctx := context.Background() - slapdOut := new(bytes.Buffer) + slapd, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ + ContainerRequest: req, + Started: true, + }) + if err != nil { + if slapd != nil { + logs, err := slapd.Logs(ctx) + if err == nil { + defer logs.Close() - cmd := exec.Command( - "slapd", - "-d", "any", - "-h", "ldap://localhost:10389/ ldaps://localhost:10636/ ldapi://"+socketPath, - "-f", configPath, - ) - cmd.Stdout = slapdOut - cmd.Stderr = slapdOut - if err := cmd.Start(); err != nil { - t.Fatal(err) - } - - var ( - // Wait group finishes once slapd has exited. - // - // Use a wait group because multiple goroutines can't listen on - // cmd.Wait(). It triggers the race detector. - wg = new(sync.WaitGroup) - // Ensure only one condition can set the slapdFailed boolean. - once = new(sync.Once) - slapdFailed bool - ) - - wg.Add(1) - go func() { cmd.Wait(); wg.Done() }() - - defer func() { - if slapdFailed { - // If slapd exited before it was killed, print its logs. - t.Logf("%s\n", slapdOut) + logLines, err := ioutil.ReadAll(logs) + if err != nil { + t.Log(string(logLines)) + } + } } - }() - go func() { - wg.Wait() - once.Do(func() { slapdFailed = true }) - }() - - defer func() { - once.Do(func() { slapdFailed = false }) - cmd.Process.Kill() - wg.Wait() - }() - - // Try a few times to connect to the LDAP server. On slower machines - // it can take a while for it to come up. - connected := false - wait := 100 * time.Millisecond - for i := 0; i < 5; i++ { - time.Sleep(wait) - - ldapadd := exec.Command( - "ldapadd", "-x", - "-D", "cn=admin,dc=example,dc=org", - "-w", "admin", - "-f", schemaPath, - "-H", "ldap://localhost:10389/", - ) - if out, err := ldapadd.CombinedOutput(); err != nil { - t.Logf("ldapadd: %s", out) - wait = wait * 2 // backoff - continue - } - connected = true - break + t.Fatal(err) } - if !connected { - t.Errorf("ldapadd command failed") - return + defer slapd.Terminate(ctx) + + ip, err := slapd.Host(ctx) + if err != nil { + t.Fatal(err) + } + port, err := slapd.MappedPort(ctx, "389") + if err != nil { + t.Fatal(err) + } + tlsPort, err := slapd.MappedPort(ctx, "636") + if err != nil { + t.Fatal(err) } // Shallow copy. @@ -858,17 +760,17 @@ func runTests(t *testing.T, schema string, connMethod connectionMethod, config * // group search configuration. switch connMethod { case connectStartTLS: - c.Host = "localhost:10389" - c.RootCA = "testdata/ca.crt" + c.Host = fmt.Sprintf("%s:%s", ip, port.Port()) + c.RootCA = "testdata/certs/ca.crt" c.StartTLS = true case connectLDAPS: - c.Host = "localhost:10636" - c.RootCA = "testdata/ca.crt" + c.Host = fmt.Sprintf("%s:%s", ip, tlsPort.Port()) + c.RootCA = "testdata/certs/ca.crt" case connectInsecureSkipVerify: - c.Host = "localhost:10636" + c.Host = fmt.Sprintf("%s:%s", ip, tlsPort.Port()) c.InsecureSkipVerify = true case connectLDAP: - c.Host = "localhost:10389" + c.Host = fmt.Sprintf("%s:%s", ip, port.Port()) c.InsecureNoSSL = true } @@ -934,98 +836,3 @@ func runTests(t *testing.T, schema string, connMethod connectionMethod, config * }) } } - -// Standard OpenLDAP schema files to include. -// -// These are copied from the /etc/openldap/schema directory. -var includeFiles = []string{ - "core.schema", - "cosine.schema", - "inetorgperson.schema", - "misc.schema", - "nis.schema", - "openldap.schema", -} - -// tmplData is the struct used to execute the SLAPD config template. -type tmplData struct { - // Directory for database to be writen to. - TempDir string - // List of schema files to include. - Includes []string - // TLS assets for LDAPS. - TLSKeyPath string - TLSCertPath string -} - -// Config template copied from: -// http://www.zytrax.com/books/ldap/ch5/index.html#step1-slapd -// -// TLS instructions found here: -// http://www.openldap.org/doc/admin24/tls.html -var slapdConfigTmpl = template.Must(template.New("").Parse(` -{{ range $i, $include := .Includes }} -include {{ $include }} -{{ end }} - -# MODULELOAD definitions -# not required (comment out) before version 2.3 -moduleload back_bdb.la - -database bdb -suffix "dc=example,dc=org" - -# root or superuser -rootdn "cn=admin,dc=example,dc=org" -rootpw admin -# The database directory MUST exist prior to running slapd AND -# change path as necessary -directory {{ .TempDir }} - -TLSCertificateFile {{ .TLSCertPath }} -TLSCertificateKeyFile {{ .TLSKeyPath }} - -# Indices to maintain for this directory -# unique id so equality match only -index uid eq -# allows general searching on commonname, givenname and email -index cn,gn,mail eq,sub -# allows multiple variants on surname searching -index sn eq,sub -# sub above includes subintial,subany,subfinal -# optimise department searches -index ou eq -# if searches will include objectClass uncomment following -# index objectClass eq -# shows use of default index parameter -index default eq,sub -# indices missing - uses default eq,sub -index telephonenumber - -# other database parameters -# read more in slapd.conf reference section -cachesize 10000 -checkpoint 128 15 -`)) - -func tlsAssets(t *testing.T, wd string) (certPath, keyPath string) { - certPath = filepath.Join(wd, "testdata", "server.crt") - keyPath = filepath.Join(wd, "testdata", "server.key") - for _, p := range []string{certPath, keyPath} { - if _, err := os.Stat(p); err != nil { - t.Fatalf("failed to find TLS asset file: %s %v", p, err) - } - } - return -} - -func includes(t *testing.T, wd string) (paths []string) { - for _, f := range includeFiles { - p := filepath.Join(wd, "testdata", f) - if _, err := os.Stat(p); err != nil { - t.Fatalf("failed to find schema file: %s %v", p, err) - } - paths = append(paths, p) - } - return -} diff --git a/connector/ldap/testdata/ca.crt b/connector/ldap/testdata/certs/ca.crt similarity index 100% rename from connector/ldap/testdata/ca.crt rename to connector/ldap/testdata/certs/ca.crt diff --git a/connector/ldap/testdata/ca.key b/connector/ldap/testdata/certs/ca.key similarity index 100% rename from connector/ldap/testdata/ca.key rename to connector/ldap/testdata/certs/ca.key diff --git a/connector/ldap/testdata/certs/dhparam.pem b/connector/ldap/testdata/certs/dhparam.pem new file mode 100644 index 00000000..1a69cd70 --- /dev/null +++ b/connector/ldap/testdata/certs/dhparam.pem @@ -0,0 +1,8 @@ +-----BEGIN DH PARAMETERS----- +MIIBCAKCAQEAx5y2viJKOAAcDYSj55odZsbA7dkSQ9afEPd9uaCLOvRYKLJY1S1V +C4m1eVfna8JndSLdsBGDQe4BlBTkEYMYR8CJHtUuBxeAucOH8KlF8rIHXXi71oex +T7kPtJEDINQKOn06bHqNcn0a7ZMWP8jiQ708OYr5P+1T/N82QTAFpDuqK42ZnBqf +8qzQkkTN0UCktY2EWnFTbNIXcMKWQnYP8zt/CG3Q31b2bnQt2iLEa/DIF7RLNjfx +9wPQBBAqgWbLmWfdPpHsAPtQxtItb+GRbPs3aLm06CFKlQuteDoP+suo0EtglHcV +V9Ynvdz0cdJCJ7EPyET6CtLMzc/Puup/AwIBAg== +-----END DH PARAMETERS----- diff --git a/connector/ldap/testdata/server.crt b/connector/ldap/testdata/certs/ldap.crt similarity index 100% rename from connector/ldap/testdata/server.crt rename to connector/ldap/testdata/certs/ldap.crt diff --git a/connector/ldap/testdata/server.key b/connector/ldap/testdata/certs/ldap.key similarity index 100% rename from connector/ldap/testdata/server.key rename to connector/ldap/testdata/certs/ldap.key diff --git a/connector/ldap/testdata/core.schema b/connector/ldap/testdata/core.schema deleted file mode 100644 index 3ae58187..00000000 --- a/connector/ldap/testdata/core.schema +++ /dev/null @@ -1,610 +0,0 @@ -# OpenLDAP Core schema -# $OpenLDAP$ -## This work is part of OpenLDAP Software . -## -## Copyright 1998-2016 The OpenLDAP Foundation. -## All rights reserved. -## -## Redistribution and use in source and binary forms, with or without -## modification, are permitted only as authorized by the OpenLDAP -## Public License. -## -## A copy of this license is available in the file LICENSE in the -## top-level directory of the distribution or, alternatively, at -## . -# -## Portions Copyright (C) The Internet Society (1997-2006). -## All Rights Reserved. -## -## This document and translations of it may be copied and furnished to -## others, and derivative works that comment on or otherwise explain it -## or assist in its implementation may be prepared, copied, published -## and distributed, in whole or in part, without restriction of any -## kind, provided that the above copyright notice and this paragraph are -## included on all such copies and derivative works. However, this -## document itself may not be modified in any way, such as by removing -## the copyright notice or references to the Internet Society or other -## Internet organizations, except as needed for the purpose of -## developing Internet standards in which case the procedures for -## copyrights defined in the Internet Standards process must be -## followed, or as required to translate it into languages other than -## English. -## -## The limited permissions granted above are perpetual and will not be -## revoked by the Internet Society or its successors or assigns. -## -## This document and the information contained herein is provided on an -## "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING -## TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING -## BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION -## HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF -## MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. - -# -# -# Includes LDAPv3 schema items from: -# RFC 2252/2256 (LDAPv3) -# -# Select standard track schema items: -# RFC 1274 (uid/dc) -# RFC 2079 (URI) -# RFC 2247 (dc/dcObject) -# RFC 2587 (PKI) -# RFC 2589 (Dynamic Directory Services) -# RFC 4524 (associatedDomain) -# -# Select informational schema items: -# RFC 2377 (uidObject) - -# -# Standard attribute types from RFC 2256 -# - -# system schema -#attributetype ( 2.5.4.0 NAME 'objectClass' -# DESC 'RFC2256: object classes of the entity' -# EQUALITY objectIdentifierMatch -# SYNTAX 1.3.6.1.4.1.1466.115.121.1.38 ) - -# system schema -#attributetype ( 2.5.4.1 NAME ( 'aliasedObjectName' 'aliasedEntryName' ) -# DESC 'RFC2256: name of aliased object' -# EQUALITY distinguishedNameMatch -# SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE ) - -attributetype ( 2.5.4.2 NAME 'knowledgeInformation' - DESC 'RFC2256: knowledge information' - EQUALITY caseIgnoreMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{32768} ) - -# system schema -#attributetype ( 2.5.4.3 NAME ( 'cn' 'commonName' ) -# DESC 'RFC2256: common name(s) for which the entity is known by' -# SUP name ) - -attributetype ( 2.5.4.4 NAME ( 'sn' 'surname' ) - DESC 'RFC2256: last (family) name(s) for which the entity is known by' - SUP name ) - -attributetype ( 2.5.4.5 NAME 'serialNumber' - DESC 'RFC2256: serial number of the entity' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.44{64} ) - -# RFC 4519 definition ('countryName' in X.500 and RFC2256) -attributetype ( 2.5.4.6 NAME ( 'c' 'countryName' ) - DESC 'RFC4519: two-letter ISO-3166 country code' - SUP name - SYNTAX 1.3.6.1.4.1.1466.115.121.1.11 - SINGLE-VALUE ) - -#attributetype ( 2.5.4.6 NAME ( 'c' 'countryName' ) -# DESC 'RFC2256: ISO-3166 country 2-letter code' -# SUP name SINGLE-VALUE ) - -attributetype ( 2.5.4.7 NAME ( 'l' 'localityName' ) - DESC 'RFC2256: locality which this object resides in' - SUP name ) - -attributetype ( 2.5.4.8 NAME ( 'st' 'stateOrProvinceName' ) - DESC 'RFC2256: state or province which this object resides in' - SUP name ) - -attributetype ( 2.5.4.9 NAME ( 'street' 'streetAddress' ) - DESC 'RFC2256: street address of this object' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} ) - -attributetype ( 2.5.4.10 NAME ( 'o' 'organizationName' ) - DESC 'RFC2256: organization this object belongs to' - SUP name ) - -attributetype ( 2.5.4.11 NAME ( 'ou' 'organizationalUnitName' ) - DESC 'RFC2256: organizational unit this object belongs to' - SUP name ) - -attributetype ( 2.5.4.12 NAME 'title' - DESC 'RFC2256: title associated with the entity' - SUP name ) - -# system schema -#attributetype ( 2.5.4.13 NAME 'description' -# DESC 'RFC2256: descriptive information' -# EQUALITY caseIgnoreMatch -# SUBSTR caseIgnoreSubstringsMatch -# SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} ) - -# Deprecated by enhancedSearchGuide -attributetype ( 2.5.4.14 NAME 'searchGuide' - DESC 'RFC2256: search guide, deprecated by enhancedSearchGuide' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.25 ) - -attributetype ( 2.5.4.15 NAME 'businessCategory' - DESC 'RFC2256: business category' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} ) - -attributetype ( 2.5.4.16 NAME 'postalAddress' - DESC 'RFC2256: postal address' - EQUALITY caseIgnoreListMatch - SUBSTR caseIgnoreListSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.41 ) - -attributetype ( 2.5.4.17 NAME 'postalCode' - DESC 'RFC2256: postal code' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{40} ) - -attributetype ( 2.5.4.18 NAME 'postOfficeBox' - DESC 'RFC2256: Post Office Box' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{40} ) - -attributetype ( 2.5.4.19 NAME 'physicalDeliveryOfficeName' - DESC 'RFC2256: Physical Delivery Office Name' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} ) - -attributetype ( 2.5.4.20 NAME 'telephoneNumber' - DESC 'RFC2256: Telephone Number' - EQUALITY telephoneNumberMatch - SUBSTR telephoneNumberSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.50{32} ) - -attributetype ( 2.5.4.21 NAME 'telexNumber' - DESC 'RFC2256: Telex Number' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.52 ) - -attributetype ( 2.5.4.22 NAME 'teletexTerminalIdentifier' - DESC 'RFC2256: Teletex Terminal Identifier' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.51 ) - -attributetype ( 2.5.4.23 NAME ( 'facsimileTelephoneNumber' 'fax' ) - DESC 'RFC2256: Facsimile (Fax) Telephone Number' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.22 ) - -attributetype ( 2.5.4.24 NAME 'x121Address' - DESC 'RFC2256: X.121 Address' - EQUALITY numericStringMatch - SUBSTR numericStringSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.36{15} ) - -attributetype ( 2.5.4.25 NAME 'internationaliSDNNumber' - DESC 'RFC2256: international ISDN number' - EQUALITY numericStringMatch - SUBSTR numericStringSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.36{16} ) - -attributetype ( 2.5.4.26 NAME 'registeredAddress' - DESC 'RFC2256: registered postal address' - SUP postalAddress - SYNTAX 1.3.6.1.4.1.1466.115.121.1.41 ) - -attributetype ( 2.5.4.27 NAME 'destinationIndicator' - DESC 'RFC2256: destination indicator' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.44{128} ) - -attributetype ( 2.5.4.28 NAME 'preferredDeliveryMethod' - DESC 'RFC2256: preferred delivery method' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.14 - SINGLE-VALUE ) - -attributetype ( 2.5.4.29 NAME 'presentationAddress' - DESC 'RFC2256: presentation address' - EQUALITY presentationAddressMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.43 - SINGLE-VALUE ) - -attributetype ( 2.5.4.30 NAME 'supportedApplicationContext' - DESC 'RFC2256: supported application context' - EQUALITY objectIdentifierMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.38 ) - -attributetype ( 2.5.4.31 NAME 'member' - DESC 'RFC2256: member of a group' - SUP distinguishedName ) - -attributetype ( 2.5.4.32 NAME 'owner' - DESC 'RFC2256: owner (of the object)' - SUP distinguishedName ) - -attributetype ( 2.5.4.33 NAME 'roleOccupant' - DESC 'RFC2256: occupant of role' - SUP distinguishedName ) - -# system schema -#attributetype ( 2.5.4.34 NAME 'seeAlso' -# DESC 'RFC2256: DN of related object' -# SUP distinguishedName ) - -# system schema -#attributetype ( 2.5.4.35 NAME 'userPassword' -# DESC 'RFC2256/2307: password of user' -# EQUALITY octetStringMatch -# SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{128} ) - -# Must be transferred using ;binary -# with certificateExactMatch rule (per X.509) -attributetype ( 2.5.4.36 NAME 'userCertificate' - DESC 'RFC2256: X.509 user certificate, use ;binary' - EQUALITY certificateExactMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.8 ) - -# Must be transferred using ;binary -# with certificateExactMatch rule (per X.509) -attributetype ( 2.5.4.37 NAME 'cACertificate' - DESC 'RFC2256: X.509 CA certificate, use ;binary' - EQUALITY certificateExactMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.8 ) - -# Must be transferred using ;binary -attributetype ( 2.5.4.38 NAME 'authorityRevocationList' - DESC 'RFC2256: X.509 authority revocation list, use ;binary' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.9 ) - -# Must be transferred using ;binary -attributetype ( 2.5.4.39 NAME 'certificateRevocationList' - DESC 'RFC2256: X.509 certificate revocation list, use ;binary' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.9 ) - -# Must be stored and requested in the binary form -attributetype ( 2.5.4.40 NAME 'crossCertificatePair' - DESC 'RFC2256: X.509 cross certificate pair, use ;binary' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.10 ) - -# system schema -#attributetype ( 2.5.4.41 NAME 'name' -# EQUALITY caseIgnoreMatch -# SUBSTR caseIgnoreSubstringsMatch -# SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{32768} ) - -attributetype ( 2.5.4.42 NAME ( 'givenName' 'gn' ) - DESC 'RFC2256: first name(s) for which the entity is known by' - SUP name ) - -attributetype ( 2.5.4.43 NAME 'initials' - DESC 'RFC2256: initials of some or all of names, but not the surname(s).' - SUP name ) - -attributetype ( 2.5.4.44 NAME 'generationQualifier' - DESC 'RFC2256: name qualifier indicating a generation' - SUP name ) - -attributetype ( 2.5.4.45 NAME 'x500UniqueIdentifier' - DESC 'RFC2256: X.500 unique identifier' - EQUALITY bitStringMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.6 ) - -attributetype ( 2.5.4.46 NAME 'dnQualifier' - DESC 'RFC2256: DN qualifier' - EQUALITY caseIgnoreMatch - ORDERING caseIgnoreOrderingMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.44 ) - -attributetype ( 2.5.4.47 NAME 'enhancedSearchGuide' - DESC 'RFC2256: enhanced search guide' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.21 ) - -attributetype ( 2.5.4.48 NAME 'protocolInformation' - DESC 'RFC2256: protocol information' - EQUALITY protocolInformationMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.42 ) - -# system schema -#attributetype ( 2.5.4.49 NAME 'distinguishedName' -# EQUALITY distinguishedNameMatch -# SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 ) - -attributetype ( 2.5.4.50 NAME 'uniqueMember' - DESC 'RFC2256: unique member of a group' - EQUALITY uniqueMemberMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.34 ) - -attributetype ( 2.5.4.51 NAME 'houseIdentifier' - DESC 'RFC2256: house identifier' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{32768} ) - -# Must be transferred using ;binary -attributetype ( 2.5.4.52 NAME 'supportedAlgorithms' - DESC 'RFC2256: supported algorithms' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.49 ) - -# Must be transferred using ;binary -attributetype ( 2.5.4.53 NAME 'deltaRevocationList' - DESC 'RFC2256: delta revocation list; use ;binary' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.9 ) - -attributetype ( 2.5.4.54 NAME 'dmdName' - DESC 'RFC2256: name of DMD' - SUP name ) - -attributetype ( 2.5.4.65 NAME 'pseudonym' - DESC 'X.520(4th): pseudonym for the object' - SUP name ) - -# Standard object classes from RFC2256 - -# system schema -#objectclass ( 2.5.6.0 NAME 'top' -# DESC 'RFC2256: top of the superclass chain' -# ABSTRACT -# MUST objectClass ) - -# system schema -#objectclass ( 2.5.6.1 NAME 'alias' -# DESC 'RFC2256: an alias' -# SUP top STRUCTURAL -# MUST aliasedObjectName ) - -objectclass ( 2.5.6.2 NAME 'country' - DESC 'RFC2256: a country' - SUP top STRUCTURAL - MUST c - MAY ( searchGuide $ description ) ) - -objectclass ( 2.5.6.3 NAME 'locality' - DESC 'RFC2256: a locality' - SUP top STRUCTURAL - MAY ( street $ seeAlso $ searchGuide $ st $ l $ description ) ) - -objectclass ( 2.5.6.4 NAME 'organization' - DESC 'RFC2256: an organization' - SUP top STRUCTURAL - MUST o - MAY ( userPassword $ searchGuide $ seeAlso $ businessCategory $ - x121Address $ registeredAddress $ destinationIndicator $ - preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $ - telephoneNumber $ internationaliSDNNumber $ - facsimileTelephoneNumber $ street $ postOfficeBox $ postalCode $ - postalAddress $ physicalDeliveryOfficeName $ st $ l $ description ) ) - -objectclass ( 2.5.6.5 NAME 'organizationalUnit' - DESC 'RFC2256: an organizational unit' - SUP top STRUCTURAL - MUST ou - MAY ( userPassword $ searchGuide $ seeAlso $ businessCategory $ - x121Address $ registeredAddress $ destinationIndicator $ - preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $ - telephoneNumber $ internationaliSDNNumber $ - facsimileTelephoneNumber $ street $ postOfficeBox $ postalCode $ - postalAddress $ physicalDeliveryOfficeName $ st $ l $ description ) ) - -objectclass ( 2.5.6.6 NAME 'person' - DESC 'RFC2256: a person' - SUP top STRUCTURAL - MUST ( sn $ cn ) - MAY ( userPassword $ telephoneNumber $ seeAlso $ description ) ) - -objectclass ( 2.5.6.7 NAME 'organizationalPerson' - DESC 'RFC2256: an organizational person' - SUP person STRUCTURAL - MAY ( title $ x121Address $ registeredAddress $ destinationIndicator $ - preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $ - telephoneNumber $ internationaliSDNNumber $ - facsimileTelephoneNumber $ street $ postOfficeBox $ postalCode $ - postalAddress $ physicalDeliveryOfficeName $ ou $ st $ l ) ) - -objectclass ( 2.5.6.8 NAME 'organizationalRole' - DESC 'RFC2256: an organizational role' - SUP top STRUCTURAL - MUST cn - MAY ( x121Address $ registeredAddress $ destinationIndicator $ - preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $ - telephoneNumber $ internationaliSDNNumber $ facsimileTelephoneNumber $ - seeAlso $ roleOccupant $ preferredDeliveryMethod $ street $ - postOfficeBox $ postalCode $ postalAddress $ - physicalDeliveryOfficeName $ ou $ st $ l $ description ) ) - -objectclass ( 2.5.6.9 NAME 'groupOfNames' - DESC 'RFC2256: a group of names (DNs)' - SUP top STRUCTURAL - MUST ( member $ cn ) - MAY ( businessCategory $ seeAlso $ owner $ ou $ o $ description ) ) - -objectclass ( 2.5.6.10 NAME 'residentialPerson' - DESC 'RFC2256: an residential person' - SUP person STRUCTURAL - MUST l - MAY ( businessCategory $ x121Address $ registeredAddress $ - destinationIndicator $ preferredDeliveryMethod $ telexNumber $ - teletexTerminalIdentifier $ telephoneNumber $ internationaliSDNNumber $ - facsimileTelephoneNumber $ preferredDeliveryMethod $ street $ - postOfficeBox $ postalCode $ postalAddress $ - physicalDeliveryOfficeName $ st $ l ) ) - -objectclass ( 2.5.6.11 NAME 'applicationProcess' - DESC 'RFC2256: an application process' - SUP top STRUCTURAL - MUST cn - MAY ( seeAlso $ ou $ l $ description ) ) - -objectclass ( 2.5.6.12 NAME 'applicationEntity' - DESC 'RFC2256: an application entity' - SUP top STRUCTURAL - MUST ( presentationAddress $ cn ) - MAY ( supportedApplicationContext $ seeAlso $ ou $ o $ l $ - description ) ) - -objectclass ( 2.5.6.13 NAME 'dSA' - DESC 'RFC2256: a directory system agent (a server)' - SUP applicationEntity STRUCTURAL - MAY knowledgeInformation ) - -objectclass ( 2.5.6.14 NAME 'device' - DESC 'RFC2256: a device' - SUP top STRUCTURAL - MUST cn - MAY ( serialNumber $ seeAlso $ owner $ ou $ o $ l $ description ) ) - -objectclass ( 2.5.6.15 NAME 'strongAuthenticationUser' - DESC 'RFC2256: a strong authentication user' - SUP top AUXILIARY - MUST userCertificate ) - -objectclass ( 2.5.6.16 NAME 'certificationAuthority' - DESC 'RFC2256: a certificate authority' - SUP top AUXILIARY - MUST ( authorityRevocationList $ certificateRevocationList $ - cACertificate ) MAY crossCertificatePair ) - -objectclass ( 2.5.6.17 NAME 'groupOfUniqueNames' - DESC 'RFC2256: a group of unique names (DN and Unique Identifier)' - SUP top STRUCTURAL - MUST ( uniqueMember $ cn ) - MAY ( businessCategory $ seeAlso $ owner $ ou $ o $ description ) ) - -objectclass ( 2.5.6.18 NAME 'userSecurityInformation' - DESC 'RFC2256: a user security information' - SUP top AUXILIARY - MAY ( supportedAlgorithms ) ) - -objectclass ( 2.5.6.16.2 NAME 'certificationAuthority-V2' - SUP certificationAuthority - AUXILIARY MAY ( deltaRevocationList ) ) - -objectclass ( 2.5.6.19 NAME 'cRLDistributionPoint' - SUP top STRUCTURAL - MUST ( cn ) - MAY ( certificateRevocationList $ authorityRevocationList $ - deltaRevocationList ) ) - -objectclass ( 2.5.6.20 NAME 'dmd' - SUP top STRUCTURAL - MUST ( dmdName ) - MAY ( userPassword $ searchGuide $ seeAlso $ businessCategory $ - x121Address $ registeredAddress $ destinationIndicator $ - preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $ - telephoneNumber $ internationaliSDNNumber $ facsimileTelephoneNumber $ - street $ postOfficeBox $ postalCode $ postalAddress $ - physicalDeliveryOfficeName $ st $ l $ description ) ) - -# -# Object Classes from RFC 2587 -# -objectclass ( 2.5.6.21 NAME 'pkiUser' - DESC 'RFC2587: a PKI user' - SUP top AUXILIARY - MAY userCertificate ) - -objectclass ( 2.5.6.22 NAME 'pkiCA' - DESC 'RFC2587: PKI certificate authority' - SUP top AUXILIARY - MAY ( authorityRevocationList $ certificateRevocationList $ - cACertificate $ crossCertificatePair ) ) - -objectclass ( 2.5.6.23 NAME 'deltaCRL' - DESC 'RFC2587: PKI user' - SUP top AUXILIARY - MAY deltaRevocationList ) - -# -# Standard Track URI label schema from RFC 2079 -# system schema -#attributetype ( 1.3.6.1.4.1.250.1.57 NAME 'labeledURI' -# DESC 'RFC2079: Uniform Resource Identifier with optional label' -# EQUALITY caseExactMatch -# SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) - -objectclass ( 1.3.6.1.4.1.250.3.15 NAME 'labeledURIObject' - DESC 'RFC2079: object that contains the URI attribute type' - SUP top AUXILIARY - MAY ( labeledURI ) ) - -# -# Derived from RFC 1274, but with new "short names" -# -#attributetype ( 0.9.2342.19200300.100.1.1 -# NAME ( 'uid' 'userid' ) -# DESC 'RFC1274: user identifier' -# EQUALITY caseIgnoreMatch -# SUBSTR caseIgnoreSubstringsMatch -# SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -attributetype ( 0.9.2342.19200300.100.1.3 - NAME ( 'mail' 'rfc822Mailbox' ) - DESC 'RFC1274: RFC822 Mailbox' - EQUALITY caseIgnoreIA5Match - SUBSTR caseIgnoreIA5SubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} ) - -objectclass ( 0.9.2342.19200300.100.4.19 NAME 'simpleSecurityObject' - DESC 'RFC1274: simple security object' - SUP top AUXILIARY - MUST userPassword ) - -# RFC 1274 + RFC 2247 -attributetype ( 0.9.2342.19200300.100.1.25 - NAME ( 'dc' 'domainComponent' ) - DESC 'RFC1274/2247: domain component' - EQUALITY caseIgnoreIA5Match - SUBSTR caseIgnoreIA5SubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) - -# RFC 2247 -objectclass ( 1.3.6.1.4.1.1466.344 NAME 'dcObject' - DESC 'RFC2247: domain component object' - SUP top AUXILIARY MUST dc ) - -# RFC 2377 -objectclass ( 1.3.6.1.1.3.1 NAME 'uidObject' - DESC 'RFC2377: uid object' - SUP top AUXILIARY MUST uid ) - -# RFC 4524 -# The 'associatedDomain' attribute specifies DNS [RFC1034][RFC2181] -# host names [RFC1123] that are associated with an object. That is, -# values of this attribute should conform to the following ABNF: -# -# domain = root / label *( DOT label ) -# root = SPACE -# label = LETDIG [ *61( LETDIG / HYPHEN ) LETDIG ] -# LETDIG = %x30-39 / %x41-5A / %x61-7A ; "0" - "9" / "A"-"Z" / "a"-"z" -# SPACE = %x20 ; space (" ") -# HYPHEN = %x2D ; hyphen ("-") -# DOT = %x2E ; period (".") -attributetype ( 0.9.2342.19200300.100.1.37 - NAME 'associatedDomain' - DESC 'RFC1274: domain associated with object' - EQUALITY caseIgnoreIA5Match - SUBSTR caseIgnoreIA5SubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) - -# RFC 2459 -- deprecated in favor of 'mail' (in cosine.schema) -attributetype ( 1.2.840.113549.1.9.1 - NAME ( 'email' 'emailAddress' 'pkcs9email' ) - DESC 'RFC3280: legacy attribute for email addresses in DNs' - EQUALITY caseIgnoreIA5Match - SUBSTR caseIgnoreIA5SubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{128} ) - diff --git a/connector/ldap/testdata/cosine.schema b/connector/ldap/testdata/cosine.schema deleted file mode 100644 index a270e592..00000000 --- a/connector/ldap/testdata/cosine.schema +++ /dev/null @@ -1,2571 +0,0 @@ -# RFC1274: Cosine and Internet X.500 schema -# $OpenLDAP$ -## This work is part of OpenLDAP Software . -## -## Copyright 1998-2016 The OpenLDAP Foundation. -## All rights reserved. -## -## Redistribution and use in source and binary forms, with or without -## modification, are permitted only as authorized by the OpenLDAP -## Public License. -## -## A copy of this license is available in the file LICENSE in the -## top-level directory of the distribution or, alternatively, at -## . -# -# RFC1274: Cosine and Internet X.500 schema -# -# This file contains LDAPv3 schema derived from X.500 COSINE "pilot" -# schema. As this schema was defined for X.500(89), some -# oddities were introduced in the mapping to LDAPv3. The -# mappings were based upon: draft-ietf-asid-ldapv3-attributes-03.txt -# (a work in progress) -# -# Note: It seems that the pilot schema evolved beyond what was -# described in RFC1274. However, this document attempts to describes -# RFC1274 as published. -# -# Depends on core.schema - - -# Network Working Group P. Barker -# Request for Comments: 1274 S. Kille -# University College London -# November 1991 -# -# The COSINE and Internet X.500 Schema -# -# [trimmed] -# -# Abstract -# -# This document suggests an X.500 Directory Schema, or Naming -# Architecture, for use in the COSINE and Internet X.500 pilots. The -# schema is independent of any specific implementation. As well as -# indicating support for the standard object classes and attributes, a -# large number of generally useful object classes and attributes are -# also defined. An appendix to this document includes a machine -# processable version of the schema. -# -# [trimmed] - -# 7. Object Identifiers -# -# Some additional object identifiers are defined for this schema. -# These are also reproduced in Appendix C. -# -# data OBJECT IDENTIFIER ::= {ccitt 9} -# pss OBJECT IDENTIFIER ::= {data 2342} -# ucl OBJECT IDENTIFIER ::= {pss 19200300} -# pilot OBJECT IDENTIFIER ::= {ucl 100} -# -# pilotAttributeType OBJECT IDENTIFIER ::= {pilot 1} -# pilotAttributeSyntax OBJECT IDENTIFIER ::= {pilot 3} -# pilotObjectClass OBJECT IDENTIFIER ::= {pilot 4} -# pilotGroups OBJECT IDENTIFIER ::= {pilot 10} -# -# iA5StringSyntax OBJECT IDENTIFIER ::= {pilotAttributeSyntax 4} -# caseIgnoreIA5StringSyntax OBJECT IDENTIFIER ::= -# {pilotAttributeSyntax 5} -# -# 8. Object Classes -# [relocated after 9] - -# -# 9. Attribute Types -# -# 9.1. X.500 standard attribute types -# -# A number of generally useful attribute types are defined in X.520, -# and these are supported. Refer to that document for descriptions of -# the suggested usage of these attribute types. The ASN.1 for these -# attribute types is reproduced for completeness in Appendix C. -# -# 9.2. X.400 standard attribute types -# -# The standard X.400 attribute types are supported. See X.402 for full -# details. The ASN.1 for these attribute types is reproduced in -# Appendix C. -# -# 9.3. COSINE/Internet attribute types -# -# This section describes all the attribute types defined for use in the -# COSINE and Internet pilots. Descriptions are given as to the -# suggested usage of these attribute types. The ASN.1 for these -# attribute types is reproduced in Appendix C. -# -# 9.3.1. Userid -# -# The Userid attribute type specifies a computer system login name. -# -# userid ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-user-identifier)) -# ::= {pilotAttributeType 1} -# -#(in core.schema) -##attributetype ( 0.9.2342.19200300.100.1.1 NAME ( 'uid' 'userid' ) -## EQUALITY caseIgnoreMatch -## SUBSTR caseIgnoreSubstringsMatch -## SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.2. Text Encoded O/R Address -# -# The Text Encoded O/R Address attribute type specifies a text encoding -# of an X.400 O/R address, as specified in RFC 987. The use of this -# attribute is deprecated as the attribute is intended for interim use -# only. This attribute will be the first candidate for the attribute -# expiry mechanisms! -# -# textEncodedORAddress ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-text-encoded-or-address)) -# ::= {pilotAttributeType 2} -# -attributetype ( 0.9.2342.19200300.100.1.2 NAME 'textEncodedORAddress' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.3. RFC 822 Mailbox -# -# The RFC822 Mailbox attribute type specifies an electronic mailbox -# attribute following the syntax specified in RFC 822. Note that this -# attribute should not be used for greybook or other non-Internet order -# mailboxes. -# -# rfc822Mailbox ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreIA5StringSyntax -# (SIZE (1 .. ub-rfc822-mailbox)) -# ::= {pilotAttributeType 3} -# -#(in core.schema) -##attributetype ( 0.9.2342.19200300.100.1.3 NAME ( 'mail' 'rfc822Mailbox' ) -## EQUALITY caseIgnoreIA5Match -## SUBSTR caseIgnoreIA5SubstringsMatch -## SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} ) - -# 9.3.4. Information -# -# The Information attribute type specifies any general information -# pertinent to an object. It is recommended that specific usage of -# this attribute type is avoided, and that specific requirements are -# met by other (possibly additional) attribute types. -# -# info ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-information)) -# ::= {pilotAttributeType 4} -# -attributetype ( 0.9.2342.19200300.100.1.4 NAME 'info' - DESC 'RFC1274: general information' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{2048} ) - - -# 9.3.5. Favourite Drink -# -# The Favourite Drink attribute type specifies the favourite drink of -# an object (or person). -# -# favouriteDrink ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-favourite-drink)) -# ::= {pilotAttributeType 5} -# -attributetype ( 0.9.2342.19200300.100.1.5 - NAME ( 'drink' 'favouriteDrink' ) - DESC 'RFC1274: favorite drink' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.6. Room Number -# -# The Room Number attribute type specifies the room number of an -# object. Note that the commonName attribute should be used for naming -# room objects. -# -# roomNumber ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-room-number)) -# ::= {pilotAttributeType 6} -# -attributetype ( 0.9.2342.19200300.100.1.6 NAME 'roomNumber' - DESC 'RFC1274: room number' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.7. Photo -# -# The Photo attribute type specifies a "photograph" for an object. -# This should be encoded in G3 fax as explained in recommendation T.4, -# with an ASN.1 wrapper to make it compatible with an X.400 BodyPart as -# defined in X.420. -# -# IMPORT G3FacsimileBodyPart FROM { mhs-motis ipms modules -# information-objects } -# -# photo ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# CHOICE { -# g3-facsimile [3] G3FacsimileBodyPart -# } -# (SIZE (1 .. ub-photo)) -# ::= {pilotAttributeType 7} -# -attributetype ( 0.9.2342.19200300.100.1.7 NAME 'photo' - DESC 'RFC1274: photo (G3 fax)' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.23{25000} ) - -# 9.3.8. User Class -# -# The User Class attribute type specifies a category of computer user. -# The semantics placed on this attribute are for local interpretation. -# Examples of current usage od this attribute in academia are -# undergraduate student, researcher, lecturer, etc. Note that the -# organizationalStatus attribute may now often be preferred as it makes -# no distinction between computer users and others. -# -# userClass ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-user-class)) -# ::= {pilotAttributeType 8} -# -attributetype ( 0.9.2342.19200300.100.1.8 NAME 'userClass' - DESC 'RFC1274: category of user' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.9. Host -# -# The Host attribute type specifies a host computer. -# -# host ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-host)) -# ::= {pilotAttributeType 9} -# -attributetype ( 0.9.2342.19200300.100.1.9 NAME 'host' - DESC 'RFC1274: host computer' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.10. Manager -# -# The Manager attribute type specifies the manager of an object -# represented by an entry. -# -# manager ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# distinguishedNameSyntax -# ::= {pilotAttributeType 10} -# -attributetype ( 0.9.2342.19200300.100.1.10 NAME 'manager' - DESC 'RFC1274: DN of manager' - EQUALITY distinguishedNameMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 ) - -# 9.3.11. Document Identifier -# -# The Document Identifier attribute type specifies a unique identifier -# for a document. -# -# documentIdentifier ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-document-identifier)) -# ::= {pilotAttributeType 11} -# -attributetype ( 0.9.2342.19200300.100.1.11 NAME 'documentIdentifier' - DESC 'RFC1274: unique identifier of document' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.12. Document Title -# -# The Document Title attribute type specifies the title of a document. -# -# documentTitle ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-document-title)) -# ::= {pilotAttributeType 12} -# -attributetype ( 0.9.2342.19200300.100.1.12 NAME 'documentTitle' - DESC 'RFC1274: title of document' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.13. Document Version -# -# The Document Version attribute type specifies the version number of a -# document. -# -# documentVersion ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-document-version)) -# ::= {pilotAttributeType 13} -# -attributetype ( 0.9.2342.19200300.100.1.13 NAME 'documentVersion' - DESC 'RFC1274: version of document' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.14. Document Author -# -# The Document Author attribute type specifies the distinguished name -# of the author of a document. -# -# documentAuthor ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# distinguishedNameSyntax -# ::= {pilotAttributeType 14} -# -attributetype ( 0.9.2342.19200300.100.1.14 NAME 'documentAuthor' - DESC 'RFC1274: DN of author of document' - EQUALITY distinguishedNameMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 ) - -# 9.3.15. Document Location -# -# The Document Location attribute type specifies the location of the -# document original. -# -# documentLocation ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-document-location)) -# ::= {pilotAttributeType 15} -# -attributetype ( 0.9.2342.19200300.100.1.15 NAME 'documentLocation' - DESC 'RFC1274: location of document original' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.16. Home Telephone Number -# -# The Home Telephone Number attribute type specifies a home telephone -# number associated with a person. Attribute values should follow the -# agreed format for international telephone numbers: i.e., "+44 71 123 -# 4567". -# -# homeTelephoneNumber ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# telephoneNumberSyntax -# ::= {pilotAttributeType 20} -# -attributetype ( 0.9.2342.19200300.100.1.20 - NAME ( 'homePhone' 'homeTelephoneNumber' ) - DESC 'RFC1274: home telephone number' - EQUALITY telephoneNumberMatch - SUBSTR telephoneNumberSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.50 ) - -# 9.3.17. Secretary -# -# The Secretary attribute type specifies the secretary of a person. -# The attribute value for Secretary is a distinguished name. -# -# secretary ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# distinguishedNameSyntax -# ::= {pilotAttributeType 21} -# -attributetype ( 0.9.2342.19200300.100.1.21 NAME 'secretary' - DESC 'RFC1274: DN of secretary' - EQUALITY distinguishedNameMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 ) - -# 9.3.18. Other Mailbox -# -# The Other Mailbox attribute type specifies values for electronic -# mailbox types other than X.400 and rfc822. -# -# otherMailbox ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# SEQUENCE { -# mailboxType PrintableString, -- e.g. Telemail -# mailbox IA5String -- e.g. X378:Joe -# } -# ::= {pilotAttributeType 22} -# -attributetype ( 0.9.2342.19200300.100.1.22 NAME 'otherMailbox' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.39 ) - -# 9.3.19. Last Modified Time -# -# The Last Modified Time attribute type specifies the last time, in UTC -# time, that an entry was modified. Ideally, this attribute should be -# maintained by the DSA. -# -# lastModifiedTime ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# uTCTimeSyntax -# ::= {pilotAttributeType 23} -# -## Deprecated in favor of modifyTimeStamp -#attributetype ( 0.9.2342.19200300.100.1.23 NAME 'lastModifiedTime' -# DESC 'RFC1274: time of last modify, replaced by modifyTimestamp' -# OBSOLETE -# SYNTAX 1.3.6.1.4.1.1466.115.121.1.53 -# USAGE directoryOperation ) - -# 9.3.20. Last Modified By -# -# The Last Modified By attribute specifies the distinguished name of -# the last user to modify the associated entry. Ideally, this -# attribute should be maintained by the DSA. -# -# lastModifiedBy ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# distinguishedNameSyntax -# ::= {pilotAttributeType 24} -# -## Deprecated in favor of modifiersName -#attributetype ( 0.9.2342.19200300.100.1.24 NAME 'lastModifiedBy' -# DESC 'RFC1274: last modifier, replaced by modifiersName' -# OBSOLETE -# EQUALITY distinguishedNameMatch -# SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 -# USAGE directoryOperation ) - -# 9.3.21. Domain Component -# -# The Domain Component attribute type specifies a DNS/NRS domain. For -# example, "uk" or "ac". -# -# domainComponent ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreIA5StringSyntax -# SINGLE VALUE -# ::= {pilotAttributeType 25} -# -##(in core.schema) -##attributetype ( 0.9.2342.19200300.100.1.25 NAME ( 'dc' 'domainComponent' ) -## EQUALITY caseIgnoreIA5Match -## SUBSTR caseIgnoreIA5SubstringsMatch -## SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) - -# 9.3.22. DNS ARecord -# -# The A Record attribute type specifies a type A (Address) DNS resource -# record [6] [7]. -# -# aRecord ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# DNSRecordSyntax -# ::= {pilotAttributeType 26} -# -## incorrect syntax? -attributetype ( 0.9.2342.19200300.100.1.26 NAME 'aRecord' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) - -## missing from RFC1274 -## incorrect syntax? -attributetype ( 0.9.2342.19200300.100.1.27 NAME 'mDRecord' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) - -# 9.3.23. MX Record -# -# The MX Record attribute type specifies a type MX (Mail Exchange) DNS -# resource record [6] [7]. -# -# mXRecord ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# DNSRecordSyntax -# ::= {pilotAttributeType 28} -# -## incorrect syntax!! -attributetype ( 0.9.2342.19200300.100.1.28 NAME 'mXRecord' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) - -# 9.3.24. NS Record -# -# The NS Record attribute type specifies an NS (Name Server) DNS -# resource record [6] [7]. -# -# nSRecord ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# DNSRecordSyntax -# ::= {pilotAttributeType 29} -# -## incorrect syntax!! -attributetype ( 0.9.2342.19200300.100.1.29 NAME 'nSRecord' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) - -# 9.3.25. SOA Record -# -# The SOA Record attribute type specifies a type SOA (Start of -# Authority) DNS resorce record [6] [7]. -# -# sOARecord ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# DNSRecordSyntax -# ::= {pilotAttributeType 30} -# -## incorrect syntax!! -attributetype ( 0.9.2342.19200300.100.1.30 NAME 'sOARecord' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) - -# 9.3.26. CNAME Record -# -# The CNAME Record attribute type specifies a type CNAME (Canonical -# Name) DNS resource record [6] [7]. -# -# cNAMERecord ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# iA5StringSyntax -# ::= {pilotAttributeType 31} -# -## incorrect syntax!! -attributetype ( 0.9.2342.19200300.100.1.31 NAME 'cNAMERecord' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) - -# 9.3.27. Associated Domain -# -# The Associated Domain attribute type specifies a DNS or NRS domain -# which is associated with an object in the DIT. For example, the entry -# in the DIT with a distinguished name "C=GB, O=University College -# London" would have an associated domain of "UCL.AC.UK. Note that all -# domains should be represented in rfc822 order. See [3] for more -# details of usage of this attribute. -# -# associatedDomain ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreIA5StringSyntax -# ::= {pilotAttributeType 37} -# -#attributetype ( 0.9.2342.19200300.100.1.37 NAME 'associatedDomain' -# EQUALITY caseIgnoreIA5Match -# SUBSTR caseIgnoreIA5SubstringsMatch -# SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) - -# 9.3.28. Associated Name -# -# The Associated Name attribute type specifies an entry in the -# organisational DIT associated with a DNS/NRS domain. See [3] for -# more details of usage of this attribute. -# -# associatedName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# distinguishedNameSyntax -# ::= {pilotAttributeType 38} -# -attributetype ( 0.9.2342.19200300.100.1.38 NAME 'associatedName' - DESC 'RFC1274: DN of entry associated with domain' - EQUALITY distinguishedNameMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 ) - -# 9.3.29. Home postal address -# -# The Home postal address attribute type specifies a home postal -# address for an object. This should be limited to up to 6 lines of 30 -# characters each. -# -# homePostalAddress ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# postalAddress -# MATCHES FOR EQUALITY -# ::= {pilotAttributeType 39} -# -attributetype ( 0.9.2342.19200300.100.1.39 NAME 'homePostalAddress' - DESC 'RFC1274: home postal address' - EQUALITY caseIgnoreListMatch - SUBSTR caseIgnoreListSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.41 ) - -# 9.3.30. Personal Title -# -# The Personal Title attribute type specifies a personal title for a -# person. Examples of personal titles are "Ms", "Dr", "Prof" and "Rev". -# -# personalTitle ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-personal-title)) -# ::= {pilotAttributeType 40} -# -attributetype ( 0.9.2342.19200300.100.1.40 NAME 'personalTitle' - DESC 'RFC1274: personal title' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.31. Mobile Telephone Number -# -# The Mobile Telephone Number attribute type specifies a mobile -# telephone number associated with a person. Attribute values should -# follow the agreed format for international telephone numbers: i.e., -# "+44 71 123 4567". -# -# mobileTelephoneNumber ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# telephoneNumberSyntax -# ::= {pilotAttributeType 41} -# -attributetype ( 0.9.2342.19200300.100.1.41 - NAME ( 'mobile' 'mobileTelephoneNumber' ) - DESC 'RFC1274: mobile telephone number' - EQUALITY telephoneNumberMatch - SUBSTR telephoneNumberSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.50 ) - -# 9.3.32. Pager Telephone Number -# -# The Pager Telephone Number attribute type specifies a pager telephone -# number for an object. Attribute values should follow the agreed -# format for international telephone numbers: i.e., "+44 71 123 4567". -# -# pagerTelephoneNumber ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# telephoneNumberSyntax -# ::= {pilotAttributeType 42} -# -attributetype ( 0.9.2342.19200300.100.1.42 - NAME ( 'pager' 'pagerTelephoneNumber' ) - DESC 'RFC1274: pager telephone number' - EQUALITY telephoneNumberMatch - SUBSTR telephoneNumberSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.50 ) - -# 9.3.33. Friendly Country Name -# -# The Friendly Country Name attribute type specifies names of countries -# in human readable format. The standard attribute country name must -# be one of the two-letter codes defined in ISO 3166. -# -# friendlyCountryName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# ::= {pilotAttributeType 43} -# -attributetype ( 0.9.2342.19200300.100.1.43 - NAME ( 'co' 'friendlyCountryName' ) - DESC 'RFC1274: friendly country name' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) - -# 9.3.34. Unique Identifier -# -# The Unique Identifier attribute type specifies a "unique identifier" -# for an object represented in the Directory. The domain within which -# the identifier is unique, and the exact semantics of the identifier, -# are for local definition. For a person, this might be an -# institution-wide payroll number. For an organisational unit, it -# might be a department code. -# -# uniqueIdentifier ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-unique-identifier)) -# ::= {pilotAttributeType 44} -# -attributetype ( 0.9.2342.19200300.100.1.44 NAME 'uniqueIdentifier' - DESC 'RFC1274: unique identifer' - EQUALITY caseIgnoreMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.35. Organisational Status -# -# The Organisational Status attribute type specifies a category by -# which a person is often referred to in an organisation. Examples of -# usage in academia might include undergraduate student, researcher, -# lecturer, etc. -# -# A Directory administrator should probably consider carefully the -# distinctions between this and the title and userClass attributes. -# -# organizationalStatus ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-organizational-status)) -# ::= {pilotAttributeType 45} -# -attributetype ( 0.9.2342.19200300.100.1.45 NAME 'organizationalStatus' - DESC 'RFC1274: organizational status' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.36. Janet Mailbox -# -# The Janet Mailbox attribute type specifies an electronic mailbox -# attribute following the syntax specified in the Grey Book of the -# Coloured Book series. This attribute is intended for the convenience -# of U.K users unfamiliar with rfc822 and little-endian mail addresses. -# Entries using this attribute MUST also include an rfc822Mailbox -# attribute. -# -# janetMailbox ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreIA5StringSyntax -# (SIZE (1 .. ub-janet-mailbox)) -# ::= {pilotAttributeType 46} -# -attributetype ( 0.9.2342.19200300.100.1.46 NAME 'janetMailbox' - DESC 'RFC1274: Janet mailbox' - EQUALITY caseIgnoreIA5Match - SUBSTR caseIgnoreIA5SubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} ) - -# 9.3.37. Mail Preference Option -# -# An attribute to allow users to indicate a preference for inclusion of -# their names on mailing lists (electronic or physical). The absence -# of such an attribute should be interpreted as if the attribute was -# present with value "no-list-inclusion". This attribute should be -# interpreted by anyone using the directory to derive mailing lists, -# and its value respected. -# -# mailPreferenceOption ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX ENUMERATED { -# no-list-inclusion(0), -# any-list-inclusion(1), -- may be added to any lists -# professional-list-inclusion(2) -# -- may be added to lists -# -- which the list provider -# -- views as related to the -# -- users professional inter- -# -- ests, perhaps evaluated -# -- from the business of the -# -- organisation or keywords -# -- in the entry. -# } -# ::= {pilotAttributeType 47} -# -attributetype ( 0.9.2342.19200300.100.1.47 - NAME 'mailPreferenceOption' - DESC 'RFC1274: mail preference option' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 ) - -# 9.3.38. Building Name -# -# The Building Name attribute type specifies the name of the building -# where an organisation or organisational unit is based. -# -# buildingName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-building-name)) -# ::= {pilotAttributeType 48} -# -attributetype ( 0.9.2342.19200300.100.1.48 NAME 'buildingName' - DESC 'RFC1274: name of building' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) - -# 9.3.39. DSA Quality -# -# The DSA Quality attribute type specifies the purported quality of a -# DSA. It allows a DSA manager to indicate the expected level of -# availability of the DSA. See [8] for details of the syntax. -# -# dSAQuality ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX DSAQualitySyntax -# SINGLE VALUE -# ::= {pilotAttributeType 49} -# -attributetype ( 0.9.2342.19200300.100.1.49 NAME 'dSAQuality' - DESC 'RFC1274: DSA Quality' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.19 SINGLE-VALUE ) - -# 9.3.40. Single Level Quality -# -# The Single Level Quality attribute type specifies the purported data -# quality at the level immediately below in the DIT. See [8] for -# details of the syntax. -# -# singleLevelQuality ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX DataQualitySyntax -# SINGLE VALUE -# ::= {pilotAttributeType 50} -# -attributetype ( 0.9.2342.19200300.100.1.50 NAME 'singleLevelQuality' - DESC 'RFC1274: Single Level Quality' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.13 SINGLE-VALUE ) - -# 9.3.41. Subtree Minimum Quality -# -# The Subtree Minimum Quality attribute type specifies the purported -# minimum data quality for a DIT subtree. See [8] for more discussion -# and details of the syntax. -# -# subtreeMinimumQuality ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX DataQualitySyntax -# SINGLE VALUE -# -- Defaults to singleLevelQuality -# ::= {pilotAttributeType 51} -# -attributetype ( 0.9.2342.19200300.100.1.51 NAME 'subtreeMinimumQuality' - DESC 'RFC1274: Subtree Mininum Quality' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.13 SINGLE-VALUE ) - -# 9.3.42. Subtree Maximum Quality -# -# The Subtree Maximum Quality attribute type specifies the purported -# maximum data quality for a DIT subtree. See [8] for more discussion -# and details of the syntax. -# -# subtreeMaximumQuality ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX DataQualitySyntax -# SINGLE VALUE -# -- Defaults to singleLevelQuality -# ::= {pilotAttributeType 52} -# -attributetype ( 0.9.2342.19200300.100.1.52 NAME 'subtreeMaximumQuality' - DESC 'RFC1274: Subtree Maximun Quality' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.13 SINGLE-VALUE ) - -# 9.3.43. Personal Signature -# -# The Personal Signature attribute type allows for a representation of -# a person's signature. This should be encoded in G3 fax as explained -# in recommendation T.4, with an ASN.1 wrapper to make it compatible -# with an X.400 BodyPart as defined in X.420. -# -# IMPORT G3FacsimileBodyPart FROM { mhs-motis ipms modules -# information-objects } -# -# personalSignature ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# CHOICE { -# g3-facsimile [3] G3FacsimileBodyPart -# } -# (SIZE (1 .. ub-personal-signature)) -# ::= {pilotAttributeType 53} -# -attributetype ( 0.9.2342.19200300.100.1.53 NAME 'personalSignature' - DESC 'RFC1274: Personal Signature (G3 fax)' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.23 ) - -# 9.3.44. DIT Redirect -# -# The DIT Redirect attribute type is used to indicate that the object -# described by one entry now has a newer entry in the DIT. The entry -# containing the redirection attribute should be expired after a -# suitable grace period. This attribute may be used when an individual -# changes his/her place of work, and thus acquires a new organisational -# DN. -# -# dITRedirect ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# distinguishedNameSyntax -# ::= {pilotAttributeType 54} -# -attributetype ( 0.9.2342.19200300.100.1.54 NAME 'dITRedirect' - DESC 'RFC1274: DIT Redirect' - EQUALITY distinguishedNameMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 ) - -# 9.3.45. Audio -# -# The Audio attribute type allows the storing of sounds in the -# Directory. The attribute uses a u-law encoded sound file as used by -# the "play" utility on a Sun 4. This is an interim format. -# -# audio ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# Audio -# (SIZE (1 .. ub-audio)) -# ::= {pilotAttributeType 55} -# -attributetype ( 0.9.2342.19200300.100.1.55 NAME 'audio' - DESC 'RFC1274: audio (u-law)' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.4{25000} ) - -# 9.3.46. Publisher of Document -# -# -# The Publisher of Document attribute is the person and/or organization -# that published a document. -# -# documentPublisher ATTRIBUTE -# WITH ATTRIBUTE SYNTAX caseIgnoreStringSyntax -# ::= {pilotAttributeType 56} -# -attributetype ( 0.9.2342.19200300.100.1.56 NAME 'documentPublisher' - DESC 'RFC1274: publisher of document' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) - -# 9.4. Generally useful syntaxes -# -# caseIgnoreIA5StringSyntax ATTRIBUTE-SYNTAX -# IA5String -# MATCHES FOR EQUALITY SUBSTRINGS -# -# iA5StringSyntax ATTRIBUTE-SYNTAX -# IA5String -# MATCHES FOR EQUALITY SUBSTRINGS -# -# -# -- Syntaxes to support the DNS attributes -# -# DNSRecordSyntax ATTRIBUTE-SYNTAX -# IA5String -# MATCHES FOR EQUALITY -# -# -# NRSInformationSyntax ATTRIBUTE-SYNTAX -# NRSInformation -# MATCHES FOR EQUALITY -# -# -# NRSInformation ::= SET { -# [0] Context, -# [1] Address-space-id, -# routes [2] SEQUENCE OF SEQUENCE { -# Route-cost, -# Addressing-info } -# } -# -# -# 9.5. Upper bounds on length of attribute values -# -# -# ub-document-identifier INTEGER ::= 256 -# -# ub-document-location INTEGER ::= 256 -# -# ub-document-title INTEGER ::= 256 -# -# ub-document-version INTEGER ::= 256 -# -# ub-favourite-drink INTEGER ::= 256 -# -# ub-host INTEGER ::= 256 -# -# ub-information INTEGER ::= 2048 -# -# ub-unique-identifier INTEGER ::= 256 -# -# ub-personal-title INTEGER ::= 256 -# -# ub-photo INTEGER ::= 250000 -# -# ub-rfc822-mailbox INTEGER ::= 256 -# -# ub-room-number INTEGER ::= 256 -# -# ub-text-or-address INTEGER ::= 256 -# -# ub-user-class INTEGER ::= 256 -# -# ub-user-identifier INTEGER ::= 256 -# -# ub-organizational-status INTEGER ::= 256 -# -# ub-janet-mailbox INTEGER ::= 256 -# -# ub-building-name INTEGER ::= 256 -# -# ub-personal-signature ::= 50000 -# -# ub-audio INTEGER ::= 250000 -# - -# [back to 8] -# 8. Object Classes -# -# 8.1. X.500 standard object classes -# -# A number of generally useful object classes are defined in X.521, and -# these are supported. Refer to that document for descriptions of the -# suggested usage of these object classes. The ASN.1 for these object -# classes is reproduced for completeness in Appendix C. -# -# 8.2. X.400 standard object classes -# -# A number of object classes defined in X.400 are supported. Refer to -# X.402 for descriptions of the usage of these object classes. The -# ASN.1 for these object classes is reproduced for completeness in -# Appendix C. -# -# 8.3. COSINE/Internet object classes -# -# This section attempts to fuse together the object classes designed -# for use in the COSINE and Internet pilot activities. Descriptions -# are given of the suggested usage of these object classes. The ASN.1 -# for these object classes is also reproduced in Appendix C. -# -# 8.3.1. Pilot Object -# -# The PilotObject object class is used as a sub-class to allow some -# common, useful attributes to be assigned to entries of all other -# object classes. -# -# pilotObject OBJECT-CLASS -# SUBCLASS OF top -# MAY CONTAIN { -# info, -# photo, -# manager, -# uniqueIdentifier, -# lastModifiedTime, -# lastModifiedBy, -# dITRedirect, -# audio} -# ::= {pilotObjectClass 3} -# -#objectclass ( 0.9.2342.19200300.100.4.3 NAME 'pilotObject' -# DESC 'RFC1274: pilot object' -# SUP top AUXILIARY -# MAY ( info $ photo $ manager $ uniqueIdentifier $ -# lastModifiedTime $ lastModifiedBy $ dITRedirect $ audio ) -# ) - -# 8.3.2. Pilot Person -# -# The PilotPerson object class is used as a sub-class of person, to -# allow the use of a number of additional attributes to be assigned to -# entries of object class person. -# -# pilotPerson OBJECT-CLASS -# SUBCLASS OF person -# MAY CONTAIN { -# userid, -# textEncodedORAddress, -# rfc822Mailbox, -# favouriteDrink, -# roomNumber, -# userClass, -# homeTelephoneNumber, -# homePostalAddress, -# secretary, -# personalTitle, -# preferredDeliveryMethod, -# businessCategory, -# janetMailbox, -# otherMailbox, -# mobileTelephoneNumber, -# pagerTelephoneNumber, -# organizationalStatus, -# mailPreferenceOption, -# personalSignature} -# ::= {pilotObjectClass 4} -# -objectclass ( 0.9.2342.19200300.100.4.4 - NAME ( 'pilotPerson' 'newPilotPerson' ) - SUP person STRUCTURAL - MAY ( userid $ textEncodedORAddress $ rfc822Mailbox $ - favouriteDrink $ roomNumber $ userClass $ - homeTelephoneNumber $ homePostalAddress $ secretary $ - personalTitle $ preferredDeliveryMethod $ businessCategory $ - janetMailbox $ otherMailbox $ mobileTelephoneNumber $ - pagerTelephoneNumber $ organizationalStatus $ - mailPreferenceOption $ personalSignature ) - ) - -# 8.3.3. Account -# -# The Account object class is used to define entries representing -# computer accounts. The userid attribute should be used for naming -# entries of this object class. -# -# account OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# userid} -# MAY CONTAIN { -# description, -# seeAlso, -# localityName, -# organizationName, -# organizationalUnitName, -# host} -# ::= {pilotObjectClass 5} -# -objectclass ( 0.9.2342.19200300.100.4.5 NAME 'account' - SUP top STRUCTURAL - MUST userid - MAY ( description $ seeAlso $ localityName $ - organizationName $ organizationalUnitName $ host ) - ) - -# 8.3.4. Document -# -# The Document object class is used to define entries which represent -# documents. -# -# document OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# documentIdentifier} -# MAY CONTAIN { -# commonName, -# description, -# seeAlso, -# localityName, -# organizationName, -# organizationalUnitName, -# documentTitle, -# documentVersion, -# documentAuthor, -# documentLocation, -# documentPublisher} -# ::= {pilotObjectClass 6} -# -objectclass ( 0.9.2342.19200300.100.4.6 NAME 'document' - SUP top STRUCTURAL - MUST documentIdentifier - MAY ( commonName $ description $ seeAlso $ localityName $ - organizationName $ organizationalUnitName $ - documentTitle $ documentVersion $ documentAuthor $ - documentLocation $ documentPublisher ) - ) - -# 8.3.5. Room -# -# The Room object class is used to define entries representing rooms. -# The commonName attribute should be used for naming pentries of this -# object class. -# -# room OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# commonName} -# MAY CONTAIN { -# roomNumber, -# description, -# seeAlso, -# telephoneNumber} -# ::= {pilotObjectClass 7} -# -objectclass ( 0.9.2342.19200300.100.4.7 NAME 'room' - SUP top STRUCTURAL - MUST commonName - MAY ( roomNumber $ description $ seeAlso $ telephoneNumber ) - ) - -# 8.3.6. Document Series -# -# The Document Series object class is used to define an entry which -# represents a series of documents (e.g., The Request For Comments -# papers). -# -# documentSeries OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# commonName} -# MAY CONTAIN { -# description, -# seeAlso, -# telephoneNumber, -# localityName, -# organizationName, -# organizationalUnitName} -# ::= {pilotObjectClass 9} -# -objectclass ( 0.9.2342.19200300.100.4.9 NAME 'documentSeries' - SUP top STRUCTURAL - MUST commonName - MAY ( description $ seeAlso $ telephonenumber $ - localityName $ organizationName $ organizationalUnitName ) - ) - -# 8.3.7. Domain -# -# The Domain object class is used to define entries which represent DNS -# or NRS domains. The domainComponent attribute should be used for -# naming entries of this object class. The usage of this object class -# is described in more detail in [3]. -# -# domain OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# domainComponent} -# MAY CONTAIN { -# associatedName, -# organizationName, -# organizationalAttributeSet} -# ::= {pilotObjectClass 13} -# -objectclass ( 0.9.2342.19200300.100.4.13 NAME 'domain' - SUP top STRUCTURAL - MUST domainComponent - MAY ( associatedName $ organizationName $ description $ - businessCategory $ seeAlso $ searchGuide $ userPassword $ - localityName $ stateOrProvinceName $ streetAddress $ - physicalDeliveryOfficeName $ postalAddress $ postalCode $ - postOfficeBox $ streetAddress $ - facsimileTelephoneNumber $ internationalISDNNumber $ - telephoneNumber $ teletexTerminalIdentifier $ telexNumber $ - preferredDeliveryMethod $ destinationIndicator $ - registeredAddress $ x121Address ) - ) - -# 8.3.8. RFC822 Local Part -# -# The RFC822 Local Part object class is used to define entries which -# represent the local part of RFC822 mail addresses. This treats this -# part of an RFC822 address as a domain. The usage of this object -# class is described in more detail in [3]. -# -# rFC822localPart OBJECT-CLASS -# SUBCLASS OF domain -# MAY CONTAIN { -# commonName, -# surname, -# description, -# seeAlso, -# telephoneNumber, -# postalAttributeSet, -# telecommunicationAttributeSet} -# ::= {pilotObjectClass 14} -# -objectclass ( 0.9.2342.19200300.100.4.14 NAME 'RFC822localPart' - SUP domain STRUCTURAL - MAY ( commonName $ surname $ description $ seeAlso $ telephoneNumber $ - physicalDeliveryOfficeName $ postalAddress $ postalCode $ - postOfficeBox $ streetAddress $ - facsimileTelephoneNumber $ internationalISDNNumber $ - telephoneNumber $ teletexTerminalIdentifier $ - telexNumber $ preferredDeliveryMethod $ destinationIndicator $ - registeredAddress $ x121Address ) - ) - -# 8.3.9. DNS Domain -# -# The DNS Domain (Domain NameServer) object class is used to define -# entries for DNS domains. The usage of this object class is described -# in more detail in [3]. -# -# dNSDomain OBJECT-CLASS -# SUBCLASS OF domain -# MAY CONTAIN { -# ARecord, -# MDRecord, -# MXRecord, -# NSRecord, -# SOARecord, -# CNAMERecord} -# ::= {pilotObjectClass 15} -# -objectclass ( 0.9.2342.19200300.100.4.15 NAME 'dNSDomain' - SUP domain STRUCTURAL - MAY ( ARecord $ MDRecord $ MXRecord $ NSRecord $ - SOARecord $ CNAMERecord ) - ) - -# 8.3.10. Domain Related Object -# -# The Domain Related Object object class is used to define entries -# which represent DNS/NRS domains which are "equivalent" to an X.500 -# domain: e.g., an organisation or organisational unit. The usage of -# this object class is described in more detail in [3]. -# -# domainRelatedObject OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# associatedDomain} -# ::= {pilotObjectClass 17} -# -objectclass ( 0.9.2342.19200300.100.4.17 NAME 'domainRelatedObject' - DESC 'RFC1274: an object related to an domain' - SUP top AUXILIARY - MUST associatedDomain ) - -# 8.3.11. Friendly Country -# -# The Friendly Country object class is used to define country entries -# in the DIT. The object class is used to allow friendlier naming of -# countries than that allowed by the object class country. The naming -# attribute of object class country, countryName, has to be a 2 letter -# string defined in ISO 3166. -# -# friendlyCountry OBJECT-CLASS -# SUBCLASS OF country -# MUST CONTAIN { -# friendlyCountryName} -# ::= {pilotObjectClass 18} -# -objectclass ( 0.9.2342.19200300.100.4.18 NAME 'friendlyCountry' - SUP country STRUCTURAL - MUST friendlyCountryName ) - -# 8.3.12. Simple Security Object -# -# The Simple Security Object object class is used to allow an entry to -# have a userPassword attribute when an entry's principal object -# classes do not allow userPassword as an attribute type. -# -# simpleSecurityObject OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# userPassword } -# ::= {pilotObjectClass 19} -# -## (in core.schema) -## objectclass ( 0.9.2342.19200300.100.4.19 NAME 'simpleSecurityObject' -## SUP top AUXILIARY -## MUST userPassword ) - -# 8.3.13. Pilot Organization -# -# The PilotOrganization object class is used as a sub-class of -# organization and organizationalUnit to allow a number of additional -# attributes to be assigned to entries of object classes organization -# and organizationalUnit. -# -# pilotOrganization OBJECT-CLASS -# SUBCLASS OF organization, organizationalUnit -# MAY CONTAIN { -# buildingName} -# ::= {pilotObjectClass 20} -# -objectclass ( 0.9.2342.19200300.100.4.20 NAME 'pilotOrganization' - SUP ( organization $ organizationalUnit ) STRUCTURAL - MAY buildingName ) - -# 8.3.14. Pilot DSA -# -# The PilotDSA object class is used as a sub-class of the dsa object -# class to allow additional attributes to be assigned to entries for -# DSAs. -# -# pilotDSA OBJECT-CLASS -# SUBCLASS OF dsa -# MUST CONTAIN { -# dSAQuality} -# ::= {pilotObjectClass 21} -# -objectclass ( 0.9.2342.19200300.100.4.21 NAME 'pilotDSA' - SUP dsa STRUCTURAL - MAY dSAQuality ) - -# 8.3.15. Quality Labelled Data -# -# The Quality Labelled Data object class is used to allow the -# assignment of the data quality attributes to subtrees in the DIT. -# -# See [8] for more details. -# -# qualityLabelledData OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# dSAQuality} -# MAY CONTAIN { -# subtreeMinimumQuality, -# subtreeMaximumQuality} -# ::= {pilotObjectClass 22} -objectclass ( 0.9.2342.19200300.100.4.22 NAME 'qualityLabelledData' - SUP top AUXILIARY - MUST dsaQuality - MAY ( subtreeMinimumQuality $ subtreeMaximumQuality ) - ) - - -# References -# -# [1] CCITT/ISO, "X.500, The Directory - overview of concepts, -# models and services, CCITT /ISO IS 9594. -# -# [2] Kille, S., "The THORN and RARE X.500 Naming Architecture, in -# University College London, Department of Computer Science -# Research Note 89/48, May 1989. -# -# [3] Kille, S., "X.500 and Domains", RFC 1279, University College -# London, November 1991. -# -# [4] Rose, M., "PSI/NYSERNet White Pages Pilot Project: Status -# Report", Technical Report 90-09-10-1, published by NYSERNet -# Inc, 1990. -# -# [5] Craigie, J., "UK Academic Community Directory Service Pilot -# Project, pp. 305-310 in Computer Networks and ISDN Systems -# 17 (1989), published by North Holland. -# -# [6] Mockapetris, P., "Domain Names - Concepts and Facilities", -# RFC 1034, USC/Information Sciences Institute, November 1987. -# -# [7] Mockapetris, P., "Domain Names - Implementation and -# Specification, RFC 1035, USC/Information Sciences Institute, -# November 1987. -# -# [8] Kille, S., "Handling QOS (Quality of service) in the -# Directory," publication in process, March 1991. -# -# -# APPENDIX C - Summary of all Object Classes and Attribute Types -# -# -- Some Important Object Identifiers -# -# data OBJECT IDENTIFIER ::= {ccitt 9} -# pss OBJECT IDENTIFIER ::= {data 2342} -# ucl OBJECT IDENTIFIER ::= {pss 19200300} -# pilot OBJECT IDENTIFIER ::= {ucl 100} -# -# pilotAttributeType OBJECT IDENTIFIER ::= {pilot 1} -# pilotAttributeSyntax OBJECT IDENTIFIER ::= {pilot 3} -# pilotObjectClass OBJECT IDENTIFIER ::= {pilot 4} -# pilotGroups OBJECT IDENTIFIER ::= {pilot 10} -# -# iA5StringSyntax OBJECT IDENTIFIER ::= {pilotAttributeSyntax 4} -# caseIgnoreIA5StringSyntax OBJECT IDENTIFIER ::= -# {pilotAttributeSyntax 5} -# -# -- Standard Object Classes -# -# top OBJECT-CLASS -# MUST CONTAIN { -# objectClass} -# ::= {objectClass 0} -# -# -# alias OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# aliasedObjectName} -# ::= {objectClass 1} -# -# -# country OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# countryName} -# MAY CONTAIN { -# description, -# searchGuide} -# ::= {objectClass 2} -# -# -# locality OBJECT-CLASS -# SUBCLASS OF top -# MAY CONTAIN { -# description, -# localityName, -# stateOrProvinceName, -# searchGuide, -# seeAlso, -# streetAddress} -# ::= {objectClass 3} -# -# -# organization OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# organizationName} -# MAY CONTAIN { -# organizationalAttributeSet} -# ::= {objectClass 4} -# -# -# organizationalUnit OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# organizationalUnitName} -# MAY CONTAIN { -# organizationalAttributeSet} -# ::= {objectClass 5} -# -# -# person OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# commonName, -# surname} -# MAY CONTAIN { -# description, -# seeAlso, -# telephoneNumber, -# userPassword} -# ::= {objectClass 6} -# -# -# organizationalPerson OBJECT-CLASS -# SUBCLASS OF person -# MAY CONTAIN { -# localeAttributeSet, -# organizationalUnitName, -# postalAttributeSet, -# telecommunicationAttributeSet, -# title} -# ::= {objectClass 7} -# -# -# organizationalRole OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# commonName} -# MAY CONTAIN { -# description, -# localeAttributeSet, -# organizationalUnitName, -# postalAttributeSet, -# preferredDeliveryMethod, -# roleOccupant, -# seeAlso, -# telecommunicationAttributeSet} -# ::= {objectClass 8} -# -# -# groupOfNames OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# commonName, -# member} -# MAY CONTAIN { -# description, -# organizationName, -# organizationalUnitName, -# owner, -# seeAlso, -# businessCategory} -# ::= {objectClass 9} -# -# -# residentialPerson OBJECT-CLASS -# SUBCLASS OF person -# MUST CONTAIN { -# localityName} -# MAY CONTAIN { -# localeAttributeSet, -# postalAttributeSet, -# preferredDeliveryMethod, -# telecommunicationAttributeSet, -# businessCategory} -# ::= {objectClass 10} -# -# -# applicationProcess OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# commonName} -# MAY CONTAIN { -# description, -# localityName, -# organizationalUnitName, -# seeAlso} -# ::= {objectClass 11} -# -# -# applicationEntity OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# commonName, -# presentationAddress} -# MAY CONTAIN { -# description, -# localityName, -# organizationName, -# organizationalUnitName, -# seeAlso, -# supportedApplicationContext} -# ::= {objectClass 12} -# -# -# dSA OBJECT-CLASS -# SUBCLASS OF applicationEntity -# MAY CONTAIN { -# knowledgeInformation} -# ::= {objectClass 13} -# -# -# device OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# commonName} -# MAY CONTAIN { -# description, -# localityName, -# organizationName, -# organizationalUnitName, -# owner, -# seeAlso, -# serialNumber} -# ::= {objectClass 14} -# -# -# strongAuthenticationUser OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# userCertificate} -# ::= {objectClass 15} -# -# -# certificationAuthority OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# cACertificate, -# certificateRevocationList, -# authorityRevocationList} -# MAY CONTAIN { -# crossCertificatePair} -# ::= {objectClass 16} -# -# -- Standard MHS Object Classes -# -# mhsDistributionList OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# commonName, -# mhsDLSubmitPermissions, -# mhsORAddresses} -# MAY CONTAIN { -# description, -# organizationName, -# organizationalUnitName, -# owner, -# seeAlso, -# mhsDeliverableContentTypes, -# mhsdeliverableEits, -# mhsDLMembers, -# mhsPreferredDeliveryMethods} -# ::= {mhsObjectClass 0} -# -# -# mhsMessageStore OBJECT-CLASS -# SUBCLASS OF applicationEntity -# MAY CONTAIN { -# description, -# owner, -# mhsSupportedOptionalAttributes, -# mhsSupportedAutomaticActions, -# mhsSupportedContentTypes} -# ::= {mhsObjectClass 1} -# -# -# mhsMessageTransferAgent OBJECT-CLASS -# SUBCLASS OF applicationEntity -# MAY CONTAIN { -# description, -# owner, -# mhsDeliverableContentLength} -# ::= {mhsObjectClass 2} -# -# -# mhsOrganizationalUser OBJECT-CLASS -# SUBCLASS OF organizationalPerson -# MUST CONTAIN { -# mhsORAddresses} -# MAY CONTAIN { -# mhsDeliverableContentLength, -# mhsDeliverableContentTypes, -# mhsDeliverableEits, -# mhsMessageStoreName, -# mhsPreferredDeliveryMethods } -# ::= {mhsObjectClass 3} -# -# -# mhsResidentialUser OBJECT-CLASS -# SUBCLASS OF residentialPerson -# MUST CONTAIN { -# mhsORAddresses} -# MAY CONTAIN { -# mhsDeliverableContentLength, -# mhsDeliverableContentTypes, -# mhsDeliverableEits, -# mhsMessageStoreName, -# mhsPreferredDeliveryMethods } -# ::= {mhsObjectClass 4} -# -# -# mhsUserAgent OBJECT-CLASS -# SUBCLASS OF applicationEntity -# MAY CONTAIN { -# mhsDeliverableContentLength, -# mhsDeliverableContentTypes, -# mhsDeliverableEits, -# mhsORAddresses, -# owner} -# ::= {mhsObjectClass 5} -# -# -# -# -# -- Pilot Object Classes -# -# pilotObject OBJECT-CLASS -# SUBCLASS OF top -# MAY CONTAIN { -# info, -# photo, -# manager, -# uniqueIdentifier, -# lastModifiedTime, -# lastModifiedBy, -# dITRedirect, -# audio} -# ::= {pilotObjectClass 3} -# pilotPerson OBJECT-CLASS -# SUBCLASS OF person -# MAY CONTAIN { -# userid, -# textEncodedORAddress, -# rfc822Mailbox, -# favouriteDrink, -# roomNumber, -# userClass, -# homeTelephoneNumber, -# homePostalAddress, -# secretary, -# personalTitle, -# preferredDeliveryMethod, -# businessCategory, -# janetMailbox, -# otherMailbox, -# mobileTelephoneNumber, -# pagerTelephoneNumber, -# organizationalStatus, -# mailPreferenceOption, -# personalSignature} -# ::= {pilotObjectClass 4} -# -# -# account OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# userid} -# MAY CONTAIN { -# description, -# seeAlso, -# localityName, -# organizationName, -# organizationalUnitName, -# host} -# ::= {pilotObjectClass 5} -# -# -# document OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# documentIdentifier} -# MAY CONTAIN { -# commonName, -# description, -# seeAlso, -# localityName, -# organizationName, -# organizationalUnitName, -# documentTitle, -# documentVersion, -# documentAuthor, -# documentLocation, -# documentPublisher} -# ::= {pilotObjectClass 6} -# -# -# room OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# commonName} -# MAY CONTAIN { -# roomNumber, -# description, -# seeAlso, -# telephoneNumber} -# ::= {pilotObjectClass 7} -# -# -# documentSeries OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# commonName} -# MAY CONTAIN { -# description, -# seeAlso, -# telephoneNumber, -# localityName, -# organizationName, -# organizationalUnitName} -# ::= {pilotObjectClass 9} -# -# -# domain OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# domainComponent} -# MAY CONTAIN { -# associatedName, -# organizationName, -# organizationalAttributeSet} -# ::= {pilotObjectClass 13} -# -# -# rFC822localPart OBJECT-CLASS -# SUBCLASS OF domain -# MAY CONTAIN { -# commonName, -# surname, -# description, -# seeAlso, -# telephoneNumber, -# postalAttributeSet, -# telecommunicationAttributeSet} -# ::= {pilotObjectClass 14} -# -# -# dNSDomain OBJECT-CLASS -# SUBCLASS OF domain -# MAY CONTAIN { -# ARecord, -# MDRecord, -# MXRecord, -# NSRecord, -# SOARecord, -# CNAMERecord} -# ::= {pilotObjectClass 15} -# -# -# domainRelatedObject OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# associatedDomain} -# ::= {pilotObjectClass 17} -# -# -# friendlyCountry OBJECT-CLASS -# SUBCLASS OF country -# MUST CONTAIN { -# friendlyCountryName} -# ::= {pilotObjectClass 18} -# -# -# simpleSecurityObject OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# userPassword } -# ::= {pilotObjectClass 19} -# -# -# pilotOrganization OBJECT-CLASS -# SUBCLASS OF organization, organizationalUnit -# MAY CONTAIN { -# buildingName} -# ::= {pilotObjectClass 20} -# -# -# pilotDSA OBJECT-CLASS -# SUBCLASS OF dsa -# MUST CONTAIN { -# dSAQuality} -# ::= {pilotObjectClass 21} -# -# -# qualityLabelledData OBJECT-CLASS -# SUBCLASS OF top -# MUST CONTAIN { -# dSAQuality} -# MAY CONTAIN { -# subtreeMinimumQuality, -# subtreeMaximumQuality} -# ::= {pilotObjectClass 22} -# -# -# -# -# -- Standard Attribute Types -# -# objectClass ObjectClass -# ::= {attributeType 0} -# -# -# aliasedObjectName AliasedObjectName -# ::= {attributeType 1} -# -# -# knowledgeInformation ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreString -# ::= {attributeType 2} -# -# -# commonName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreStringSyntax -# (SIZE (1..ub-common-name)) -# ::= {attributeType 3} -# -# -# surname ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreStringSyntax -# (SIZE (1..ub-surname)) -# ::= {attributeType 4} -# -# -# serialNumber ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX printableStringSyntax -# (SIZE (1..ub-serial-number)) -# ::= {attributeType 5} -# -# -# countryName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX PrintableString -# (SIZE (1..ub-country-code)) -# SINGLE VALUE -# ::= {attributeType 6} -# -# -# localityName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreStringSyntax -# (SIZE (1..ub-locality-name)) -# ::= {attributeType 7} -# -# -# stateOrProvinceName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreStringSyntax -# (SIZE (1..ub-state-name)) -# ::= {attributeType 8} -# -# -# streetAddress ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreStringSyntax -# (SIZE (1..ub-street-address)) -# ::= {attributeType 9} -# -# -# organizationName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreStringSyntax -# (SIZE (1..ub-organization-name)) -# ::= {attributeType 10} -# -# -# organizationalUnitName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreStringSyntax -# (SIZE (1..ub-organizational-unit-name)) -# ::= {attributeType 11} -# -# -# title ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreStringSyntax -# (SIZE (1..ub-title)) -# ::= {attributeType 12} -# -# -# description ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreStringSyntax -# (SIZE (1..ub-description)) -# ::= {attributeType 13} -# -# -# searchGuide ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX Guide -# ::= {attributeType 14} -# -# -# businessCategory ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreStringSyntax -# (SIZE (1..ub-business-category)) -# ::= {attributeType 15} -# -# -# postalAddress ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX PostalAddress -# MATCHES FOR EQUALITY -# ::= {attributeType 16} -# -# -# postalCode ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreStringSyntax -# (SIZE (1..ub-postal-code)) -# ::= {attributeType 17} -# -# -# postOfficeBox ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreStringSyntax -# (SIZE (1..ub-post-office-box)) -# ::= {attributeType 18} -# -# -# physicalDeliveryOfficeName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX caseIgnoreStringSyntax -# (SIZE (1..ub-physical-office-name)) -# ::= {attributeType 19} -# -# -# telephoneNumber ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX telephoneNumberSyntax -# (SIZE (1..ub-telephone-number)) -# ::= {attributeType 20} -# -# -# telexNumber ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX TelexNumber -# (SIZE (1..ub-telex)) -# ::= {attributeType 21} -# -# -# teletexTerminalIdentifier ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX TeletexTerminalIdentifier -# (SIZE (1..ub-teletex-terminal-id)) -# ::= {attributeType 22} -# -# -# facsimileTelephoneNumber ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX FacsimileTelephoneNumber -# ::= {attributeType 23} -# -# -# x121Address ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX NumericString -# (SIZE (1..ub-x121-address)) -# ::= {attributeType 24} -# -# -# internationaliSDNNumber ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX NumericString -# (SIZE (1..ub-isdn-address)) -# ::= {attributeType 25} -# -# -# registeredAddress ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX PostalAddress -# ::= {attributeType 26} -# -# -# destinationIndicator ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX PrintableString -# (SIZE (1..ub-destination-indicator)) -# MATCHES FOR EQUALITY SUBSTRINGS -# ::= {attributeType 27} -# -# -# preferredDeliveryMethod ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX deliveryMethod -# ::= {attributeType 28} -# -# -# presentationAddress ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX PresentationAddress -# MATCHES FOR EQUALITY -# ::= {attributeType 29} -# -# -# supportedApplicationContext ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX objectIdentifierSyntax -# ::= {attributeType 30} -# -# -# member ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX distinguishedNameSyntax -# ::= {attributeType 31} -# -# -# owner ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX distinguishedNameSyntax -# ::= {attributeType 32} -# -# -# roleOccupant ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX distinguishedNameSyntax -# ::= {attributeType 33} -# -# -# seeAlso ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX distinguishedNameSyntax -# ::= {attributeType 34} -# -# -# userPassword ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX Userpassword -# ::= {attributeType 35} -# -# -# userCertificate ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX UserCertificate -# ::= {attributeType 36} -# -# -# cACertificate ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX cACertificate -# ::= {attributeType 37} -# -# -# authorityRevocationList ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX AuthorityRevocationList -# ::= {attributeType 38} -# -# -# certificateRevocationList ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX CertificateRevocationList -# ::= {attributeType 39} -# -# -# crossCertificatePair ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX CrossCertificatePair -# ::= {attributeType 40} -# -# -# -# -# -- Standard MHS Attribute Types -# -# mhsDeliverableContentLength ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX integer -# ::= {mhsAttributeType 0} -# -# -# mhsDeliverableContentTypes ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX oID -# ::= {mhsAttributeType 1} -# -# -# mhsDeliverableEits ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX oID -# ::= {mhsAttributeType 2} -# -# -# mhsDLMembers ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX oRName -# ::= {mhsAttributeType 3} -# -# -# mhsDLSubmitPermissions ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX dLSubmitPermission -# ::= {mhsAttributeType 4} -# -# -# mhsMessageStoreName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX dN -# ::= {mhsAttributeType 5} -# -# -# mhsORAddresses ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX oRAddress -# ::= {mhsAttributeType 6} -# -# -# mhsPreferredDeliveryMethods ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX deliveryMethod -# ::= {mhsAttributeType 7} -# -# -# mhsSupportedAutomaticActions ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX oID -# ::= {mhsAttributeType 8} -# -# -# mhsSupportedContentTypes ATTRIBUTE -# -# WITH ATTRIBUTE-SYNTAX oID -# ::= {mhsAttributeType 9} -# -# -# mhsSupportedOptionalAttributes ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX oID -# ::= {mhsAttributeType 10} -# -# -# -# -# -- Pilot Attribute Types -# -# userid ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-user-identifier)) -# ::= {pilotAttributeType 1} -# -# -# textEncodedORAddress ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-text-encoded-or-address)) -# ::= {pilotAttributeType 2} -# -# -# rfc822Mailbox ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreIA5StringSyntax -# (SIZE (1 .. ub-rfc822-mailbox)) -# ::= {pilotAttributeType 3} -# -# -# info ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-information)) -# ::= {pilotAttributeType 4} -# -# -# favouriteDrink ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-favourite-drink)) -# ::= {pilotAttributeType 5} -# -# -# roomNumber ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-room-number)) -# ::= {pilotAttributeType 6} -# -# -# photo ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# CHOICE { -# g3-facsimile [3] G3FacsimileBodyPart -# } -# (SIZE (1 .. ub-photo)) -# ::= {pilotAttributeType 7} -# -# -# userClass ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-user-class)) -# ::= {pilotAttributeType 8} -# -# -# host ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-host)) -# ::= {pilotAttributeType 9} -# -# -# manager ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# distinguishedNameSyntax -# ::= {pilotAttributeType 10} -# -# -# documentIdentifier ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-document-identifier)) -# ::= {pilotAttributeType 11} -# -# -# documentTitle ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-document-title)) -# ::= {pilotAttributeType 12} -# -# -# documentVersion ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-document-version)) -# ::= {pilotAttributeType 13} -# -# -# documentAuthor ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# distinguishedNameSyntax -# ::= {pilotAttributeType 14} -# -# -# documentLocation ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-document-location)) -# ::= {pilotAttributeType 15} -# -# -# homeTelephoneNumber ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# telephoneNumberSyntax -# ::= {pilotAttributeType 20} -# -# -# secretary ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# distinguishedNameSyntax -# ::= {pilotAttributeType 21} -# -# -# otherMailbox ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# SEQUENCE { -# mailboxType PrintableString, -- e.g. Telemail -# mailbox IA5String -- e.g. X378:Joe -# } -# ::= {pilotAttributeType 22} -# -# -# lastModifiedTime ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# uTCTimeSyntax -# ::= {pilotAttributeType 23} -# -# -# lastModifiedBy ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# distinguishedNameSyntax -# ::= {pilotAttributeType 24} -# -# -# domainComponent ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreIA5StringSyntax -# SINGLE VALUE -# ::= {pilotAttributeType 25} -# -# -# aRecord ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# DNSRecordSyntax -# ::= {pilotAttributeType 26} -# -# -# mXRecord ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# DNSRecordSyntax -# ::= {pilotAttributeType 28} -# -# -# nSRecord ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# DNSRecordSyntax -# ::= {pilotAttributeType 29} -# -# sOARecord ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# DNSRecordSyntax -# ::= {pilotAttributeType 30} -# -# -# cNAMERecord ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# iA5StringSyntax -# ::= {pilotAttributeType 31} -# -# -# associatedDomain ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreIA5StringSyntax -# ::= {pilotAttributeType 37} -# -# -# associatedName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# distinguishedNameSyntax -# ::= {pilotAttributeType 38} -# -# -# homePostalAddress ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# postalAddress -# MATCHES FOR EQUALITY -# ::= {pilotAttributeType 39} -# -# -# personalTitle ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-personal-title)) -# ::= {pilotAttributeType 40} -# -# -# mobileTelephoneNumber ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# telephoneNumberSyntax -# ::= {pilotAttributeType 41} -# -# -# pagerTelephoneNumber ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# telephoneNumberSyntax -# ::= {pilotAttributeType 42} -# -# -# friendlyCountryName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# ::= {pilotAttributeType 43} -# -# -# uniqueIdentifier ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-unique-identifier)) -# ::= {pilotAttributeType 44} -# -# -# organizationalStatus ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-organizational-status)) -# ::= {pilotAttributeType 45} -# -# -# janetMailbox ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreIA5StringSyntax -# (SIZE (1 .. ub-janet-mailbox)) -# ::= {pilotAttributeType 46} -# -# -# mailPreferenceOption ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX ENUMERATED { -# no-list-inclusion(0), -# any-list-inclusion(1), -- may be added to any lists -# professional-list-inclusion(2) -# -- may be added to lists -# -- which the list provider -# -- views as related to the -# -- users professional inter- -# -- ests, perhaps evaluated -# -- from the business of the -# -- organisation or keywords -# -- in the entry. -# } -# ::= {pilotAttributeType 47} -# -# -# buildingName ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# caseIgnoreStringSyntax -# (SIZE (1 .. ub-building-name)) -# ::= {pilotAttributeType 48} -# -# -# dSAQuality ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX DSAQualitySyntax -# SINGLE VALUE -# ::= {pilotAttributeType 49} -# -# -# singleLevelQuality ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX DataQualitySyntax -# SINGLE VALUE -# -# -# subtreeMinimumQuality ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX DataQualitySyntax -# SINGLE VALUE -# -- Defaults to singleLevelQuality -# ::= {pilotAttributeType 51} -# -# -# subtreeMaximumQuality ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX DataQualitySyntax -# SINGLE VALUE -# -- Defaults to singleLevelQuality -# ::= {pilotAttributeType 52} -# -# -# personalSignature ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# CHOICE { -# g3-facsimile [3] G3FacsimileBodyPart -# } -# (SIZE (1 .. ub-personal-signature)) -# ::= {pilotAttributeType 53} -# -# -# dITRedirect ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# distinguishedNameSyntax -# ::= {pilotAttributeType 54} -# -# -# audio ATTRIBUTE -# WITH ATTRIBUTE-SYNTAX -# Audio -# (SIZE (1 .. ub-audio)) -# ::= {pilotAttributeType 55} -# -# documentPublisher ATTRIBUTE -# WITH ATTRIBUTE SYNTAX caseIgnoreStringSyntax -# ::= {pilotAttributeType 56} -# -# -# -# -- Generally useful syntaxes -# -# -# caseIgnoreIA5StringSyntax ATTRIBUTE-SYNTAX -# IA5String -# MATCHES FOR EQUALITY SUBSTRINGS -# -# -# iA5StringSyntax ATTRIBUTE-SYNTAX -# IA5String -# MATCHES FOR EQUALITY SUBSTRINGS -# -# -# -- Syntaxes to support the DNS attributes -# -# DNSRecordSyntax ATTRIBUTE-SYNTAX -# IA5String -# MATCHES FOR EQUALITY -# -# -# NRSInformationSyntax ATTRIBUTE-SYNTAX -# NRSInformation -# MATCHES FOR EQUALITY -# -# -# NRSInformation ::= SET { -# [0] Context, -# [1] Address-space-id, -# routes [2] SEQUENCE OF SEQUENCE { -# Route-cost, -# Addressing-info } -# } -# -# -# -- Upper bounds on length of attribute values -# -# -# ub-document-identifier INTEGER ::= 256 -# -# ub-document-location INTEGER ::= 256 -# -# ub-document-title INTEGER ::= 256 -# -# ub-document-version INTEGER ::= 256 -# -# ub-favourite-drink INTEGER ::= 256 -# -# ub-host INTEGER ::= 256 -# -# ub-information INTEGER ::= 2048 -# -# ub-unique-identifier INTEGER ::= 256 -# -# ub-personal-title INTEGER ::= 256 -# -# ub-photo INTEGER ::= 250000 -# -# ub-rfc822-mailbox INTEGER ::= 256 -# -# ub-room-number INTEGER ::= 256 -# -# ub-text-or-address INTEGER ::= 256 -# -# ub-user-class INTEGER ::= 256 -# -# ub-user-identifier INTEGER ::= 256 -# -# ub-organizational-status INTEGER ::= 256 -# -# ub-janet-mailbox INTEGER ::= 256 -# -# ub-building-name INTEGER ::= 256 -# -# ub-personal-signature ::= 50000 -# -# ub-audio INTEGER ::= 250000 -# -# [remainder of memo trimmed] - diff --git a/connector/ldap/testdata/inetorgperson.schema b/connector/ldap/testdata/inetorgperson.schema deleted file mode 100644 index 4a7077e6..00000000 --- a/connector/ldap/testdata/inetorgperson.schema +++ /dev/null @@ -1,155 +0,0 @@ -# inetorgperson.schema -- InetOrgPerson (RFC2798) -# $OpenLDAP$ -## This work is part of OpenLDAP Software . -## -## Copyright 1998-2016 The OpenLDAP Foundation. -## All rights reserved. -## -## Redistribution and use in source and binary forms, with or without -## modification, are permitted only as authorized by the OpenLDAP -## Public License. -## -## A copy of this license is available in the file LICENSE in the -## top-level directory of the distribution or, alternatively, at -## . -# -# InetOrgPerson (RFC2798) -# -# Depends upon -# Definition of an X.500 Attribute Type and an Object Class to Hold -# Uniform Resource Identifiers (URIs) [RFC2079] -# (core.schema) -# -# A Summary of the X.500(96) User Schema for use with LDAPv3 [RFC2256] -# (core.schema) -# -# The COSINE and Internet X.500 Schema [RFC1274] (cosine.schema) - -# carLicense -# This multivalued field is used to record the values of the license or -# registration plate associated with an individual. -attributetype ( 2.16.840.1.113730.3.1.1 - NAME 'carLicense' - DESC 'RFC2798: vehicle license or registration plate' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) - -# departmentNumber -# Code for department to which a person belongs. This can also be -# strictly numeric (e.g., 1234) or alphanumeric (e.g., ABC/123). -attributetype ( 2.16.840.1.113730.3.1.2 - NAME 'departmentNumber' - DESC 'RFC2798: identifies a department within an organization' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) - -# displayName -# When displaying an entry, especially within a one-line summary list, it -# is useful to be able to identify a name to be used. Since other attri- -# bute types such as 'cn' are multivalued, an additional attribute type is -# needed. Display name is defined for this purpose. -attributetype ( 2.16.840.1.113730.3.1.241 - NAME 'displayName' - DESC 'RFC2798: preferred name to be used when displaying entries' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 - SINGLE-VALUE ) - -# employeeNumber -# Numeric or alphanumeric identifier assigned to a person, typically based -# on order of hire or association with an organization. Single valued. -attributetype ( 2.16.840.1.113730.3.1.3 - NAME 'employeeNumber' - DESC 'RFC2798: numerically identifies an employee within an organization' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 - SINGLE-VALUE ) - -# employeeType -# Used to identify the employer to employee relationship. Typical values -# used will be "Contractor", "Employee", "Intern", "Temp", "External", and -# "Unknown" but any value may be used. -attributetype ( 2.16.840.1.113730.3.1.4 - NAME 'employeeType' - DESC 'RFC2798: type of employment for a person' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) - -# jpegPhoto -# Used to store one or more images of a person using the JPEG File -# Interchange Format [JFIF]. -# Note that the jpegPhoto attribute type was defined for use in the -# Internet X.500 pilots but no referencable definition for it could be -# located. -attributetype ( 0.9.2342.19200300.100.1.60 - NAME 'jpegPhoto' - DESC 'RFC2798: a JPEG image' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.28 ) - -# preferredLanguage -# Used to indicate an individual's preferred written or spoken -# language. This is useful for international correspondence or human- -# computer interaction. Values for this attribute type MUST conform to -# the definition of the Accept-Language header field defined in -# [RFC2068] with one exception: the sequence "Accept-Language" ":" -# should be omitted. This is a single valued attribute type. -attributetype ( 2.16.840.1.113730.3.1.39 - NAME 'preferredLanguage' - DESC 'RFC2798: preferred written or spoken language for a person' - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 - SINGLE-VALUE ) - -# userSMIMECertificate -# A PKCS#7 [RFC2315] SignedData, where the content that is signed is -# ignored by consumers of userSMIMECertificate values. It is -# recommended that values have a `contentType' of data with an absent -# `content' field. Values of this attribute contain a person's entire -# certificate chain and an smimeCapabilities field [RFC2633] that at a -# minimum describes their SMIME algorithm capabilities. Values for -# this attribute are to be stored and requested in binary form, as -# 'userSMIMECertificate;binary'. If available, this attribute is -# preferred over the userCertificate attribute for S/MIME applications. -## OpenLDAP note: ";binary" transfer should NOT be used as syntax is binary -attributetype ( 2.16.840.1.113730.3.1.40 - NAME 'userSMIMECertificate' - DESC 'RFC2798: PKCS#7 SignedData used to support S/MIME' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.5 ) - -# userPKCS12 -# PKCS #12 [PKCS12] provides a format for exchange of personal identity -# information. When such information is stored in a directory service, -# the userPKCS12 attribute should be used. This attribute is to be stored -# and requested in binary form, as 'userPKCS12;binary'. The attribute -# values are PFX PDUs stored as binary data. -## OpenLDAP note: ";binary" transfer should NOT be used as syntax is binary -attributetype ( 2.16.840.1.113730.3.1.216 - NAME 'userPKCS12' - DESC 'RFC2798: personal identity information, a PKCS #12 PFX' - SYNTAX 1.3.6.1.4.1.1466.115.121.1.5 ) - - -# inetOrgPerson -# The inetOrgPerson represents people who are associated with an -# organization in some way. It is a structural class and is derived -# from the organizationalPerson which is defined in X.521 [X521]. -objectclass ( 2.16.840.1.113730.3.2.2 - NAME 'inetOrgPerson' - DESC 'RFC2798: Internet Organizational Person' - SUP organizationalPerson - STRUCTURAL - MAY ( - audio $ businessCategory $ carLicense $ departmentNumber $ - displayName $ employeeNumber $ employeeType $ givenName $ - homePhone $ homePostalAddress $ initials $ jpegPhoto $ - labeledURI $ mail $ manager $ mobile $ o $ pager $ - photo $ roomNumber $ secretary $ uid $ userCertificate $ - x500uniqueIdentifier $ preferredLanguage $ - userSMIMECertificate $ userPKCS12 ) - ) diff --git a/connector/ldap/testdata/misc.schema b/connector/ldap/testdata/misc.schema deleted file mode 100644 index f01118f1..00000000 --- a/connector/ldap/testdata/misc.schema +++ /dev/null @@ -1,75 +0,0 @@ -# misc.schema -- assorted schema definitions -# $OpenLDAP$ -## This work is part of OpenLDAP Software . -## -## Copyright 1998-2016 The OpenLDAP Foundation. -## All rights reserved. -## -## Redistribution and use in source and binary forms, with or without -## modification, are permitted only as authorized by the OpenLDAP -## Public License. -## -## A copy of this license is available in the file LICENSE in the -## top-level directory of the distribution or, alternatively, at -## . -# -# Assorted definitions from several sources, including -# ''works in progress''. Contents of this file are -# subject to change (including deletion) without notice. -# -# Not recommended for production use! -# Use with extreme caution! - -#----------------------------------------------------------- -# draft-lachman-laser-ldap-mail-routing-02.txt !!!EXPIRED!!! -# (a work in progress) -# -attributetype ( 2.16.840.1.113730.3.1.13 - NAME 'mailLocalAddress' - DESC 'RFC822 email address of this recipient' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} ) - -attributetype ( 2.16.840.1.113730.3.1.18 - NAME 'mailHost' - DESC 'FQDN of the SMTP/MTA of this recipient' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} - SINGLE-VALUE ) - -attributetype ( 2.16.840.1.113730.3.1.47 - NAME 'mailRoutingAddress' - DESC 'RFC822 routing address of this recipient' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} - SINGLE-VALUE ) - -# I-D leaves this OID TBD. -# iPlanet uses 2.16.840.1.113.730.3.2.147 but that is an -# improperly delegated OID. A typo is likely. -objectclass ( 2.16.840.1.113730.3.2.147 - NAME 'inetLocalMailRecipient' - DESC 'Internet local mail recipient' - SUP top AUXILIARY - MAY ( mailLocalAddress $ mailHost $ mailRoutingAddress ) ) - -#----------------------------------------------------------- -# draft-srivastava-ldap-mail-00.txt !!!EXPIRED!!! -# (a work in progress) -# -attributetype ( 1.3.6.1.4.1.42.2.27.2.1.15 - NAME 'rfc822MailMember' - DESC 'rfc822 mail address of group member(s)' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) - -#----------------------------------------------------------- -# !!!no I-D!!! -# (a work in progress) -# -objectclass ( 1.3.6.1.4.1.42.2.27.1.2.5 - NAME 'nisMailAlias' - DESC 'NIS mail alias' - SUP top STRUCTURAL - MUST cn - MAY rfc822MailMember ) diff --git a/connector/ldap/testdata/nis.schema b/connector/ldap/testdata/nis.schema deleted file mode 100644 index 7d8e1c3d..00000000 --- a/connector/ldap/testdata/nis.schema +++ /dev/null @@ -1,237 +0,0 @@ -# $OpenLDAP$ -## This work is part of OpenLDAP Software . -## -## Copyright 1998-2016 The OpenLDAP Foundation. -## All rights reserved. -## -## Redistribution and use in source and binary forms, with or without -## modification, are permitted only as authorized by the OpenLDAP -## Public License. -## -## A copy of this license is available in the file LICENSE in the -## top-level directory of the distribution or, alternatively, at -## . - -# Definitions from RFC2307 (Experimental) -# An Approach for Using LDAP as a Network Information Service - -# Depends upon core.schema and cosine.schema - -# Note: The definitions in RFC2307 are given in syntaxes closely related -# to those in RFC2252, however, some liberties are taken that are not -# supported by RFC2252. This file has been written following RFC2252 -# strictly. - -# OID Base is iso(1) org(3) dod(6) internet(1) directory(1) nisSchema(1). -# i.e. nisSchema in RFC2307 is 1.3.6.1.1.1 -# -# Syntaxes are under 1.3.6.1.1.1.0 (two new syntaxes are defined) -# validaters for these syntaxes are incomplete, they only -# implement printable string validation (which is good as the -# common use of these syntaxes violates the specification). -# Attribute types are under 1.3.6.1.1.1.1 -# Object classes are under 1.3.6.1.1.1.2 - -# Attribute Type Definitions - -# builtin -#attributetype ( 1.3.6.1.1.1.1.0 NAME 'uidNumber' -# DESC 'An integer uniquely identifying a user in an administrative domain' -# EQUALITY integerMatch -# SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) - -# builtin -#attributetype ( 1.3.6.1.1.1.1.1 NAME 'gidNumber' -# DESC 'An integer uniquely identifying a group in an administrative domain' -# EQUALITY integerMatch -# SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.2 NAME 'gecos' - DESC 'The GECOS field; the common name' - EQUALITY caseIgnoreIA5Match - SUBSTR caseIgnoreIA5SubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.3 NAME 'homeDirectory' - DESC 'The absolute path to the home directory' - EQUALITY caseExactIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.4 NAME 'loginShell' - DESC 'The path to the login shell' - EQUALITY caseExactIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.5 NAME 'shadowLastChange' - EQUALITY integerMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.6 NAME 'shadowMin' - EQUALITY integerMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.7 NAME 'shadowMax' - EQUALITY integerMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.8 NAME 'shadowWarning' - EQUALITY integerMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.9 NAME 'shadowInactive' - EQUALITY integerMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.10 NAME 'shadowExpire' - EQUALITY integerMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.11 NAME 'shadowFlag' - EQUALITY integerMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.12 NAME 'memberUid' - EQUALITY caseExactIA5Match - SUBSTR caseExactIA5SubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) - -attributetype ( 1.3.6.1.1.1.1.13 NAME 'memberNisNetgroup' - EQUALITY caseExactIA5Match - SUBSTR caseExactIA5SubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) - -attributetype ( 1.3.6.1.1.1.1.14 NAME 'nisNetgroupTriple' - DESC 'Netgroup triple' - SYNTAX 1.3.6.1.1.1.0.0 ) - -attributetype ( 1.3.6.1.1.1.1.15 NAME 'ipServicePort' - EQUALITY integerMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.16 NAME 'ipServiceProtocol' - SUP name ) - -attributetype ( 1.3.6.1.1.1.1.17 NAME 'ipProtocolNumber' - EQUALITY integerMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.18 NAME 'oncRpcNumber' - EQUALITY integerMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.19 NAME 'ipHostNumber' - DESC 'IP address' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{128} ) - -attributetype ( 1.3.6.1.1.1.1.20 NAME 'ipNetworkNumber' - DESC 'IP network' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{128} SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.21 NAME 'ipNetmaskNumber' - DESC 'IP netmask' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{128} SINGLE-VALUE ) - -attributetype ( 1.3.6.1.1.1.1.22 NAME 'macAddress' - DESC 'MAC address' - EQUALITY caseIgnoreIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{128} ) - -attributetype ( 1.3.6.1.1.1.1.23 NAME 'bootParameter' - DESC 'rpc.bootparamd parameter' - SYNTAX 1.3.6.1.1.1.0.1 ) - -attributetype ( 1.3.6.1.1.1.1.24 NAME 'bootFile' - DESC 'Boot image name' - EQUALITY caseExactIA5Match - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) - -attributetype ( 1.3.6.1.1.1.1.26 NAME 'nisMapName' - SUP name ) - -attributetype ( 1.3.6.1.1.1.1.27 NAME 'nisMapEntry' - EQUALITY caseExactIA5Match - SUBSTR caseExactIA5SubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{1024} SINGLE-VALUE ) - -# Object Class Definitions - -objectclass ( 1.3.6.1.1.1.2.0 NAME 'posixAccount' - DESC 'Abstraction of an account with POSIX attributes' - SUP top AUXILIARY - MUST ( cn $ uid $ uidNumber $ gidNumber $ homeDirectory ) - MAY ( userPassword $ loginShell $ gecos $ description ) ) - -objectclass ( 1.3.6.1.1.1.2.1 NAME 'shadowAccount' - DESC 'Additional attributes for shadow passwords' - SUP top AUXILIARY - MUST uid - MAY ( userPassword $ shadowLastChange $ shadowMin $ - shadowMax $ shadowWarning $ shadowInactive $ - shadowExpire $ shadowFlag $ description ) ) - -objectclass ( 1.3.6.1.1.1.2.2 NAME 'posixGroup' - DESC 'Abstraction of a group of accounts' - SUP top STRUCTURAL - MUST ( cn $ gidNumber ) - MAY ( userPassword $ memberUid $ description ) ) - -objectclass ( 1.3.6.1.1.1.2.3 NAME 'ipService' - DESC 'Abstraction an Internet Protocol service' - SUP top STRUCTURAL - MUST ( cn $ ipServicePort $ ipServiceProtocol ) - MAY ( description ) ) - -objectclass ( 1.3.6.1.1.1.2.4 NAME 'ipProtocol' - DESC 'Abstraction of an IP protocol' - SUP top STRUCTURAL - MUST ( cn $ ipProtocolNumber $ description ) - MAY description ) - -objectclass ( 1.3.6.1.1.1.2.5 NAME 'oncRpc' - DESC 'Abstraction of an ONC/RPC binding' - SUP top STRUCTURAL - MUST ( cn $ oncRpcNumber $ description ) - MAY description ) - -objectclass ( 1.3.6.1.1.1.2.6 NAME 'ipHost' - DESC 'Abstraction of a host, an IP device' - SUP top AUXILIARY - MUST ( cn $ ipHostNumber ) - MAY ( l $ description $ manager ) ) - -objectclass ( 1.3.6.1.1.1.2.7 NAME 'ipNetwork' - DESC 'Abstraction of an IP network' - SUP top STRUCTURAL - MUST ( cn $ ipNetworkNumber ) - MAY ( ipNetmaskNumber $ l $ description $ manager ) ) - -objectclass ( 1.3.6.1.1.1.2.8 NAME 'nisNetgroup' - DESC 'Abstraction of a netgroup' - SUP top STRUCTURAL - MUST cn - MAY ( nisNetgroupTriple $ memberNisNetgroup $ description ) ) - -objectclass ( 1.3.6.1.1.1.2.9 NAME 'nisMap' - DESC 'A generic abstraction of a NIS map' - SUP top STRUCTURAL - MUST nisMapName - MAY description ) - -objectclass ( 1.3.6.1.1.1.2.10 NAME 'nisObject' - DESC 'An entry in a NIS map' - SUP top STRUCTURAL - MUST ( cn $ nisMapEntry $ nisMapName ) - MAY description ) - -objectclass ( 1.3.6.1.1.1.2.11 NAME 'ieee802Device' - DESC 'A device with a MAC address' - SUP top AUXILIARY - MAY macAddress ) - -objectclass ( 1.3.6.1.1.1.2.12 NAME 'bootableDevice' - DESC 'A device with boot parameters' - SUP top AUXILIARY - MAY ( bootFile $ bootParameter ) ) diff --git a/connector/ldap/testdata/openldap.schema b/connector/ldap/testdata/openldap.schema deleted file mode 100644 index 594fc8aa..00000000 --- a/connector/ldap/testdata/openldap.schema +++ /dev/null @@ -1,54 +0,0 @@ -# $OpenLDAP$ -## This work is part of OpenLDAP Software . -## -## Copyright 1998-2016 The OpenLDAP Foundation. -## All rights reserved. -## -## Redistribution and use in source and binary forms, with or without -## modification, are permitted only as authorized by the OpenLDAP -## Public License. -## -## A copy of this license is available in the file LICENSE in the -## top-level directory of the distribution or, alternatively, at -## . - -# -# OpenLDAP Project's directory schema items -# -# depends upon: -# core.schema -# cosine.schema -# inetorgperson.schema -# -# These are provided for informational purposes only. - -objectIdentifier OpenLDAProot 1.3.6.1.4.1.4203 - -objectIdentifier OpenLDAP OpenLDAProot:1 -objectIdentifier OpenLDAPattributeType OpenLDAP:3 -objectIdentifier OpenLDAPobjectClass OpenLDAP:4 - -objectClass ( OpenLDAPobjectClass:3 - NAME 'OpenLDAPorg' - DESC 'OpenLDAP Organizational Object' - SUP organization - MAY ( buildingName $ displayName $ labeledURI ) ) - -objectClass ( OpenLDAPobjectClass:4 - NAME 'OpenLDAPou' - DESC 'OpenLDAP Organizational Unit Object' - SUP organizationalUnit - MAY ( buildingName $ displayName $ labeledURI $ o ) ) - -objectClass ( OpenLDAPobjectClass:5 - NAME 'OpenLDAPperson' - DESC 'OpenLDAP Person' - SUP ( pilotPerson $ inetOrgPerson ) - MUST ( uid $ cn ) - MAY ( givenName $ labeledURI $ o ) ) - -objectClass ( OpenLDAPobjectClass:6 - NAME 'OpenLDAPdisplayableObject' - DESC 'OpenLDAP Displayable Object' - AUXILIARY - MAY displayName ) diff --git a/go.mod b/go.mod index 739a38ef..99a51004 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,7 @@ module github.com/dexidp/dex require ( + github.com/Microsoft/hcsshim v0.8.7 // indirect github.com/beevik/etree v1.1.0 github.com/coreos/bbolt v1.3.3 // indirect github.com/coreos/etcd v3.3.13+incompatible @@ -12,7 +13,6 @@ require ( github.com/felixge/httpsnoop v1.0.0 github.com/ghodss/yaml v1.0.0 github.com/go-sql-driver/mysql v1.4.1 - github.com/gogo/protobuf v1.2.1 // indirect github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 // indirect github.com/golang/protobuf v1.3.2 github.com/google/btree v1.0.0 // indirect @@ -29,16 +29,15 @@ require ( github.com/kylelemons/godebug v1.1.0 github.com/lib/pq v1.2.0 github.com/mattn/go-sqlite3 v1.11.0 - github.com/pkg/errors v0.8.1 // indirect github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35 // indirect github.com/prometheus/client_golang v1.0.0 github.com/prometheus/common v0.6.0 // indirect - github.com/prometheus/procfs v0.0.3 // indirect github.com/russellhaering/goxmldsig v0.0.0-20180430223755-7acd5e4a6ef7 github.com/sirupsen/logrus v1.4.2 github.com/soheilhy/cmux v0.1.4 // indirect github.com/spf13/cobra v0.0.5 github.com/stretchr/testify v1.3.0 + github.com/testcontainers/testcontainers-go v0.0.9 github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 // indirect github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2 // indirect go.etcd.io/bbolt v1.3.3 // indirect @@ -49,7 +48,6 @@ require ( golang.org/x/lint v0.0.0-20190409202823-959b441ac422 golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7 golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 - golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a // indirect golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 // indirect golang.org/x/tools v0.0.0-20190813214729-9dba7caff850 // indirect google.golang.org/api v0.10.0 diff --git a/go.sum b/go.sum index 9cf627f7..73f3b2e1 100644 --- a/go.sum +++ b/go.sum @@ -3,7 +3,15 @@ cloud.google.com/go v0.34.0 h1:eOI3/cP2VTU6uZLDYAoic+eyzzB9YyGmJ7eIjl8rOPg= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.38.0 h1:ROfEUZz+Gh5pa62DJWXSaonyu3StP6EA6lPEXPI6mCo= cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 h1:w+iIsaOQNcT7OZ575w+acHgRric5iCyQh+xv+KJ4HB8= +github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Microsoft/go-winio v0.4.11 h1:zoIOcVf0xPN1tnMVbTtEdI+P8OofVk3NObnwOQ6nK2Q= +github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA= +github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5 h1:ygIc8M6trr62pF5DucadTWGdEB4mEyvzi0e2nbcmcyA= +github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5/go.mod h1:tTuCMEN+UleMWgg9dVx4Hu52b1bJo+59jBh3ajtinzw= +github.com/Microsoft/hcsshim v0.8.7 h1:ptnOoufxGSzauVTsdE+wMYnCWA301PdoN4xg5oRdZpg= +github.com/Microsoft/hcsshim v0.8.7/go.mod h1:OHd7sQqRFrYd3RmSgbgji+ctCwkbq2wbEYNSzOYtcBQ= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= @@ -12,7 +20,19 @@ github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62 github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0 h1:HWo1m869IqiPhD389kmkxeTalrjNbbJTC8LXupb+sl0= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/blang/semver v3.1.0+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= +github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4= +github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/containerd/cgroups v0.0.0-20190919134610-bf292b21730f/go.mod h1:OApqhQ4XNSNC13gXIwDjhOQxjWa/NxkwZXJ1EvqT0ko= +github.com/containerd/console v0.0.0-20180822173158-c12b1e7919c1/go.mod h1:Tj/on1eG8kiEhd0+fhSDzsPAFESxzBBvdyEgyryXffw= +github.com/containerd/containerd v1.3.0-beta.2.0.20190828155532-0293cbd26c69/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= +github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc h1:TP+534wVlf61smEIq1nwLLAjQVEK2EADoW3CX9AuT+8= +github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= +github.com/containerd/fifo v0.0.0-20190226154929-a9fb20d87448/go.mod h1:ODA38xgv3Kuk8dQz2ZQXpnv/UZZUHUCL7pnLehbXgQI= +github.com/containerd/go-runc v0.0.0-20180907222934-5a6d9f37cfa3/go.mod h1:IV7qH3hrUgRmyYrtgEeGWJfWbgcHL9CSRruz2Vqcph0= +github.com/containerd/ttrpc v0.0.0-20190828154514-0e0f228740de/go.mod h1:PvCDdDGpgqzQIzDW1TphrGLssLDZp2GuS+X5DkEJB8o= +github.com/containerd/typeurl v0.0.0-20180627222232-a93fcdb778cd/go.mod h1:Cm3kwCdlkCfMSHURc+r6fwoGH6/F1hH3S4sg0rLFWPc= github.com/coreos/bbolt v1.3.3 h1:n6AiVyVRKQFNb6mJlwESEvvLoDyiTzXX7ORAUlkeBdY= github.com/coreos/bbolt v1.3.3/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= @@ -25,6 +45,7 @@ github.com/coreos/go-semver v0.2.0 h1:3Jm3tLmsgAYcjC+4Up7hJrFBPr+n7rAqYeSw/SZazu github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-semver v0.3.0 h1:wkHLiw0WNATZnSG7epLsujiMCgPAc9xhjJ4tgnAxmfM= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f h1:JOrtw2xFKzlg+cbHpyrpLDmnN1HqhBfnX7WDiW7eG2c= github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f h1:lBNOc5arjvs8E5mO2tbpBpLoyyu8B6e44T7hJy6potg= @@ -35,19 +56,34 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/docker/distribution v2.7.1-0.20190205005809-0d3efadf0154+incompatible h1:dvc1KSkIYTVjZgHf/CTC2diTYC8PzhaA5sFISRfNVrE= +github.com/docker/distribution v2.7.1-0.20190205005809-0d3efadf0154+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/docker v0.7.3-0.20190506211059-b20a14b54661 h1:ZuxGvIvF01nfc/G9RJ5Q7Va1zQE2WJyG18Zv3DqCEf4= +github.com/docker/docker v0.7.3-0.20190506211059-b20a14b54661/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-units v0.3.3 h1:Xk8S3Xj5sLGlG5g67hJmYMmUgXv5N4PhkjJHHqrwnTk= +github.com/docker/go-units v0.3.3/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw= +github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/felixge/httpsnoop v1.0.0 h1:gh8fMGz0rlOv/1WmRZm7OgncIOTsAj21iNJot48omJQ= github.com/felixge/httpsnoop v1.0.0/go.mod h1:3+D9sFq0ahK/JeJPhCBUV1xlf4/eIYrUQaxulT0VzX8= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-redis/redis v6.15.6+incompatible h1:H9evprGPLI8+ci7fxQx6WNZHJSb7be8FqJQRhdQZ5Sg= +github.com/go-redis/redis v6.15.6+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA= github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/godbus/dbus v0.0.0-20190422162347-ade71ed3457e/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= github.com/gogo/protobuf v1.1.1 h1:72R+M5VuhED/KujmZVcIquuo8mBgX4oVda//DQb3PXo= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.1 h1:/s5zKNz0uPFCZ5hddgPdo2TK2TVrUNMn0OOX8/aZMTE= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= @@ -72,13 +108,15 @@ github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OI github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/handlers v1.4.2 h1:0QniY0USkHQ1RGCLfKxeNHK9bkDHGRYGNDFBCS+YARg= github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ= +github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/grpc-ecosystem/go-grpc-middleware v1.0.0 h1:BWIsLfhgKhV5g/oF34aRjniBHLTZe5DNekSjbAjIS6c= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.0 h1:Iju5GlWwrvL6UBg4zJJt3btmonfrMlCDdsejg4CZE7c= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= @@ -86,10 +124,14 @@ github.com/grpc-ecosystem/grpc-gateway v1.9.5 h1:UImYN5qQ8tuGpGE16ZmjvcTtTw24zw1 github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/gtank/cryptopasta v0.0.0-20170601214702-1f550f6f2f69 h1:7xsUJsB2NrdcttQPa7JLEaGzvdbk7KvfrjgHZXOQRo0= github.com/gtank/cryptopasta v0.0.0-20170601214702-1f550f6f2f69/go.mod h1:YLEMZOtU+AZ7dhN9T/IpGhXVGly2bvkJQ+zxj3WeVQo= +github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v0.0.0-20161216184304-ed905158d874/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jonboulle/clockwork v0.1.0 h1:VKV+ZcuP6l3yW9doeqz6ziZGgcynBVQO+obU0+0hcPo= @@ -127,7 +169,24 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c h1:nXxl5PrvVm2L/wCy8dQu6DMTwH4oIuGN8GJDAlqDdVE= +github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.8.0 h1:VkHVNpR4iVnU8XQR6DBm8BqYjN7CRzw+xKUbVVbbW9w= +github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo= +github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/opencontainers/go-digest v0.0.0-20180430190053-c9281466c8b2/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= +github.com/opencontainers/go-digest v1.0.0-rc1 h1:WzifXhOVOEOuFYOJAW6aQqW0TooG2iki3E3Ii+WN7gQ= +github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= +github.com/opencontainers/image-spec v1.0.1 h1:JMemWkRwHx4Zj+fVxWoMCFm/8sYGGrUVojFA6h/TRcI= +github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/opencontainers/runc v0.0.0-20190115041553-12f6a991201f/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= +github.com/opencontainers/runc v0.1.1 h1:GlxAyO6x8rfZYN9Tt0Kti5a/cP41iuiO2yYT0IJGY8Y= +github.com/opencontainers/runc v0.1.1/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= +github.com/opencontainers/runtime-spec v0.1.2-0.20190507144316-5b71a03e2700/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/runtime-tools v0.0.0-20181011054405-1d69bd0f9c39/go.mod h1:r3f7wjNzSs2extwzU3Y+6pKfobzPh+kKFJ3ofN+3nfs= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= @@ -147,13 +206,16 @@ github.com/prometheus/common v0.6.0 h1:kRhiuYSXR3+uv2IbVbZhUxK5zVD/2pp3Gd2PpvPkp github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.0.3 h1:CTwfnzjQ+8dS6MhHHu4YswVAD99sL2wjPqP+VkURmKE= -github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= +github.com/prometheus/procfs v0.0.5 h1:3+auTFlqw+ZaQYJARz6ArODtkaIwtvBTx3N2NehQlL8= +github.com/prometheus/procfs v0.0.5/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/russellhaering/goxmldsig v0.0.0-20180430223755-7acd5e4a6ef7 h1:J4AOUcOh/t1XbQcJfkEqhzgvMJ2tDxdCVvmHxW5QXao= github.com/russellhaering/goxmldsig v0.0.0-20180430223755-7acd5e4a6ef7/go.mod h1:Oz4y6ImuOQZxynhbSXk7btjEfNBtGlj2dcaOvXl2FSM= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/soheilhy/cmux v0.1.4 h1:0HKaf1o97UwFjHH9o5XsHUOF+tqmdA7KEzXLpiyaw0E= @@ -172,9 +234,16 @@ github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1 github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/syndtr/gocapability v0.0.0-20170704070218-db04d3cc01c8/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= +github.com/testcontainers/testcontainers-go v0.0.9 h1:mwvFz+FkuQMqQ9oLkG4cVzPsZTRmrCo2NcaerJNaptA= +github.com/testcontainers/testcontainers-go v0.0.9/go.mod h1:0Qe9qqjNZgxHzzdHPWwmQ2D49FFO7920hLdJ4yUJXJI= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 h1:LnC5Kc/wtumK+WB441p7ynQJzVuNRJiqddSIE3IlSEQ= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/urfave/cli v0.0.0-20171014202726-7bc6a0acffa5/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v0.0.0-20180618132009-1d523034197f/go.mod h1:5yf86TLmAcydyeJq5YvxkGPE2fm/u4myDekKRoLuqhs= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2 h1:eY9dn8+vbi4tKz5Qo6v2eYzo7kUS51QINcR5jNpbZS8= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= @@ -182,6 +251,8 @@ go.etcd.io/bbolt v1.3.3 h1:MUGmc65QhB3pIlaQ5bB4LwqSj6GIonVJXpZiaKNyaKk= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.21.0 h1:mU6zScU4U1YAFPHEHYk+3JC4SY7JxgkqS10ZOSyksNg= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0 h1:C9hSCOW830chIVkdja34wa6Ky+IzWllkUinR+BtRZd4= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= @@ -204,12 +275,14 @@ golang.org/x/lint v0.0.0-20190409202823-959b441ac422 h1:QzoH/1pFpZguR8NrRHLcO6jK golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -225,19 +298,24 @@ golang.org/x/sync v0.0.0-20181108010431-42b317875d0f h1:Bl/8QSvNqXvPGPGXa2z5xUTm golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181228144115-9a3f9b0469bb/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190514135907-3a4b5fb9f71f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ= -golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3 h1:7TYNF4UdlohbFwpNH04CoPMp1cHUZgO1Ebq5r2hIjfo= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= @@ -246,6 +324,8 @@ golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxb golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 h1:SvFZT6jyqRaOeXpc5h/JSfZenJ2O330aBsf7JfSUXmQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180810170437-e96c4e24768d/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= @@ -268,9 +348,11 @@ google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64 h1:iKtrH9Y8mcbADOP0YFaEMth7OfuHY9xHOwNj4znpM1A= google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.23.0 h1:AzbTB6ux+okLTzP8Ru1Xs41C303zdcfEht7MQnYJt5A= @@ -281,16 +363,25 @@ gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d/go.mod h1:cuepJuh7vyXfUy gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/ldap.v2 v2.5.1 h1:wiu0okdNfjlBzg6UWvd1Hn8Y+Ux17/u/4nlk4CQr6tU= gopkg.in/ldap.v2 v2.5.1/go.mod h1:oI0cpe/D7HRtBQl8aTg+ZmzFUAvu4lsv3eLXMLGFxWk= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/square/go-jose.v2 v2.3.1 h1:SK5KegNXmKmqE342YYN2qPHEnUYeoMiXXl1poUlI+o4= gopkg.in/square/go-jose.v2 v2.3.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gotest.tools v0.0.0-20181223230014-1083505acf35/go.mod h1:R//lfYlUuTOTfblYI3lGoAAAebUdzjvbmQsuB7Ykd90= +gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= +gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= +honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +k8s.io/kubernetes v1.13.0/go.mod h1:ocZa8+6APFNC2tX1DZASIbocyYT5jHzqFVsY5aoB7Jk= From 11c2499713be8044bc62c7eff37b103afe5f3b83 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Sun, 8 Dec 2019 20:22:09 +0100 Subject: [PATCH 60/72] Allow ldap tests --- .github/workflows/ci.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a127d5b0..f626b106 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,8 +62,7 @@ jobs: DEX_POSTGRES_HOST: localhost DEX_POSTGRES_PORT: ${{ job.services.postgres.ports[5432] }} DEX_ETCD_ENDPOINTS: http://localhost:${{ job.services.etcd.ports[2379] }} - # TODO: enable - DEX_LDAP_TESTS: 0 + DEX_LDAP_TESTS: 1 DEX_KEYSTONE_URL: http://localhost:${{ job.services.keystone.ports[5000] }} DEX_KEYSTONE_ADMIN_URL: http://localhost:${{ job.services.keystone.ports[35357] }} DEX_KEYSTONE_ADMIN_USER: demo From 3c7593f87bf9f9efc0ea4d4931cfb85825f69d90 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Sun, 8 Dec 2019 20:41:28 +0100 Subject: [PATCH 61/72] Revert using vendored dependencies --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f626b106..3027be5f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,7 @@ jobs: name: Build runs-on: ubuntu-16.04 env: - GOFLAGS: -mod=vendor + GOFLAGS: -mod=readonly services: postgres: From 9346e328ef8616a85d10031419ecf8488dc8c265 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 18 Dec 2019 14:55:52 +0100 Subject: [PATCH 62/72] Add golangci linter --- .github/workflows/ci.yml | 3 +++ .golangci.yml | 45 ++++++++++++++++++++++++++++++++++++++++ Makefile | 23 +++++++++++++++++--- 3 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 .golangci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3027be5f..46c9c928 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,6 +71,9 @@ jobs: - name: Run Kubernetes tests run: ./scripts/test-k8s.sh + - name: Run linter + run: make lint + # Ensure proto generation doesn't depend on external packages. - name: Verify proto run: make verify-proto diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 00000000..824484d6 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,45 @@ +run: + skip-dirs: + - vendor + +linters-settings: + golint: + min-confidence: 0.1 + goimports: + local-prefixes: github.com/dexidp/dex + +linters: + enable-all: true + disable: + - funlen + - maligned + - wsl + + # TODO: fix me + - unused + - structcheck + - stylecheck + - deadcode + - misspell + - unparam + - goimports + - golint + - whitespace + - goconst + - unconvert + - bodyclose + - staticcheck + - nakedret + - ineffassign + - errcheck + - gosec + - gochecknoinits + - gochecknoglobals + - prealloc + - scopelint + - lll + - dupl + - gocritic + - gocyclo + - gocognit + - godox diff --git a/Makefile b/Makefile index 820e7ea3..c1c6d788 100644 --- a/Makefile +++ b/Makefile @@ -18,6 +18,9 @@ export GOBIN=$(PWD)/bin LD_FLAGS="-w -X $(REPO_PATH)/version.Version=$(VERSION)" +# Dependency versions +GOLANGCI_VERSION = 1.21.0 + build: bin/dex bin/example-app bin/grpc-client bin/dex: @@ -45,13 +48,27 @@ test: testrace: @go test -v --race ./... +bin/golangci-lint: bin/golangci-lint-${GOLANGCI_VERSION} + @ln -sf golangci-lint-${GOLANGCI_VERSION} bin/golangci-lint +bin/golangci-lint-${GOLANGCI_VERSION}: + curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | BINARY=golangci-lint bash -s -- v${GOLANGCI_VERSION} + @mv bin/golangci-lint $@ + +.PHONY: lint +lint: bin/golangci-lint ## Run linter + bin/golangci-lint run + +.PHONY: fix +fix: bin/golangci-lint ## Fix lint violations + bin/golangci-lint run --fix + vet: @go vet ./... fmt: @./scripts/gofmt ./... -lint: bin/golint +oldlint: bin/golint @./bin/golint -set_exit_status $(shell go list ./...) .PHONY: docker-image @@ -79,8 +96,8 @@ bin/golint: clean: @rm -rf bin/ -testall: testrace vet fmt lint +testall: testrace vet fmt oldlint FORCE: -.PHONY: test testrace vet fmt lint testall +.PHONY: test testrace vet fmt oldlint testall From bcd47fc6f37c7d51222faf248ed7a08e58448b81 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 18 Dec 2019 15:07:53 +0100 Subject: [PATCH 63/72] Remove old lint targets --- Makefile | 17 ++--------------- scripts/gofmt | 7 ------- 2 files changed, 2 insertions(+), 22 deletions(-) delete mode 100755 scripts/gofmt diff --git a/Makefile b/Makefile index c1c6d788..2c041408 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,6 @@ PROJ=dex ORG_PATH=github.com/dexidp REPO_PATH=$(ORG_PATH)/$(PROJ) export PATH := $(PWD)/bin:$(PATH) -THIS_DIRECTORY:=$(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) VERSION ?= $(shell ./scripts/git-version) @@ -62,15 +61,6 @@ lint: bin/golangci-lint ## Run linter fix: bin/golangci-lint ## Fix lint violations bin/golangci-lint run --fix -vet: - @go vet ./... - -fmt: - @./scripts/gofmt ./... - -oldlint: bin/golint - @./bin/golint -set_exit_status $(shell go list ./...) - .PHONY: docker-image docker-image: @sudo docker build -t $(DOCKER_IMAGE) . @@ -90,14 +80,11 @@ bin/protoc: scripts/get-protoc bin/protoc-gen-go: @go install -v $(REPO_PATH)/vendor/github.com/golang/protobuf/protoc-gen-go -bin/golint: - @go install -v $(THIS_DIRECTORY)/vendor/golang.org/x/lint/golint - clean: @rm -rf bin/ -testall: testrace vet fmt oldlint +testall: testrace FORCE: -.PHONY: test testrace vet fmt oldlint testall +.PHONY: test testrace testall diff --git a/scripts/gofmt b/scripts/gofmt deleted file mode 100755 index 8851bdab..00000000 --- a/scripts/gofmt +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/bash -e - -result=$( go fmt $@ ) -if [[ $result != "" ]]; then - >&2 echo "The following files are not formatted correctly: $result" - exit 1 -fi From 8c3dc0ca66e86d0af52bc0f056aaf0ddb3fe8c2a Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 18 Dec 2019 15:46:49 +0100 Subject: [PATCH 64/72] Remove unused code (fixed: unused, structcheck, deadcode linters) --- .golangci.yml | 3 --- connector/google/google.go | 1 - server/templates.go | 13 ------------- 3 files changed, 17 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 824484d6..45cfc35f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -16,10 +16,7 @@ linters: - wsl # TODO: fix me - - unused - - structcheck - stylecheck - - deadcode - misspell - unparam - goimports diff --git a/connector/google/google.go b/connector/google/google.go index 84e5580d..7561ca4d 100644 --- a/connector/google/google.go +++ b/connector/google/google.go @@ -105,7 +105,6 @@ type googleConnector struct { redirectURI string oauth2Config *oauth2.Config verifier *oidc.IDTokenVerifier - ctx context.Context cancel context.CancelFunc logger log.Logger hostedDomains []string diff --git a/server/templates.go b/server/templates.go index 88aeace0..13dda8f1 100644 --- a/server/templates.go +++ b/server/templates.go @@ -47,19 +47,6 @@ type webConfig struct { extra map[string]string } -func join(base, path string) string { - b := strings.HasSuffix(base, "/") - p := strings.HasPrefix(path, "/") - switch { - case b && p: - return base + path[1:] - case b || p: - return base + path - default: - return base + "/" + path - } -} - func dirExists(dir string) error { stat, err := os.Stat(dir) if err != nil { From 142c96c210a8a5b856b91c79b148ff8e59eaf448 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 18 Dec 2019 15:50:36 +0100 Subject: [PATCH 65/72] Fix stylecheck --- .golangci.yml | 1 - cmd/example-app/main.go | 4 +-- connector/saml/saml.go | 8 ++--- storage/kubernetes/client.go | 58 ++++++++++++++++++------------------ 4 files changed, 35 insertions(+), 36 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 45cfc35f..5bfe3e99 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -16,7 +16,6 @@ linters: - wsl # TODO: fix me - - stylecheck - misspell - unparam - goimports diff --git a/cmd/example-app/main.go b/cmd/example-app/main.go index a21b2e86..c16ddfdf 100644 --- a/cmd/example-app/main.go +++ b/cmd/example-app/main.go @@ -143,7 +143,7 @@ func cmd() *cobra.Command { ctx := oidc.ClientContext(context.Background(), a.client) provider, err := oidc.NewProvider(ctx, issuerURL) if err != nil { - return fmt.Errorf("Failed to query provider %q: %v", issuerURL, err) + return fmt.Errorf("failed to query provider %q: %v", issuerURL, err) } var s struct { @@ -153,7 +153,7 @@ func cmd() *cobra.Command { ScopesSupported []string `json:"scopes_supported"` } if err := provider.Claims(&s); err != nil { - return fmt.Errorf("Failed to parse provider scopes_supported: %v", err) + return fmt.Errorf("failed to parse provider scopes_supported: %v", err) } if len(s.ScopesSupported) == 0 { diff --git a/connector/saml/saml.go b/connector/saml/saml.go index 09414ea3..f4e52a69 100644 --- a/connector/saml/saml.go +++ b/connector/saml/saml.go @@ -325,7 +325,7 @@ func (p *provider) HandlePOST(s connector.Scopes, samlResponse, inResponseTo str // Status is a required element. if resp.Status == nil { - return ident, fmt.Errorf("Response did not contain a Status element") + return ident, fmt.Errorf("response did not contain a Status element") } if err = p.validateStatus(resp.Status); err != nil { @@ -398,7 +398,7 @@ func (p *provider) HandlePOST(s connector.Scopes, samlResponse, inResponseTo str if len(p.allowedGroups) > 0 && (!s.Groups || p.groupsAttr == "") { // allowedGroups set but no groups or groupsAttr. Disallowing. - return ident, fmt.Errorf("User not a member of allowed groups") + return ident, fmt.Errorf("user not a member of allowed groups") } // Grab the groups. @@ -427,7 +427,7 @@ func (p *provider) HandlePOST(s connector.Scopes, samlResponse, inResponseTo str if len(groupMatches) == 0 { // No group membership matches found, disallowing - return ident, fmt.Errorf("User not a member of allowed groups") + return ident, fmt.Errorf("user not a member of allowed groups") } // Otherwise, we're good @@ -468,7 +468,7 @@ func (p *provider) validateStatus(status *status) error { func (p *provider) validateSubject(subject *subject, inResponseTo string) error { // Optional according to the spec, but again, we're going to be strict here. if len(subject.SubjectConfirmations) == 0 { - return fmt.Errorf("Subject contained no SubjectConfirmations") + return fmt.Errorf("subject contained no SubjectConfirmations") } var errs []error diff --git a/storage/kubernetes/client.go b/storage/kubernetes/client.go index f2af0e57..795dcc22 100644 --- a/storage/kubernetes/client.go +++ b/storage/kubernetes/client.go @@ -55,14 +55,14 @@ type client struct { } // idToName maps an arbitrary ID, such as an email or client ID to a Kubernetes object name. -func (c *client) idToName(s string) string { - return idToName(s, c.hash) +func (cli *client) idToName(s string) string { + return idToName(s, cli.hash) } // offlineTokenName maps two arbitrary IDs, to a single Kubernetes object name. // This is used when more than one field is used to uniquely identify the object. -func (c *client) offlineTokenName(userID string, connID string) string { - return offlineTokenName(userID, connID, c.hash) +func (cli *client) offlineTokenName(userID string, connID string) string { + return offlineTokenName(userID, connID, cli.hash) } // Kubernetes names must match the regexp '[a-z0-9]([-a-z0-9]*[a-z0-9])?'. @@ -79,7 +79,7 @@ func offlineTokenName(userID string, connID string, h func() hash.Hash) string { return strings.TrimRight(encoding.EncodeToString(hash.Sum(nil)), "=") } -func (c *client) urlFor(apiVersion, namespace, resource, name string) string { +func (cli *client) urlFor(apiVersion, namespace, resource, name string) string { basePath := "apis/" if apiVersion == "v1" { basePath = "api/" @@ -91,10 +91,10 @@ func (c *client) urlFor(apiVersion, namespace, resource, name string) string { } else { p = path.Join(basePath, apiVersion, resource, name) } - if strings.HasSuffix(c.baseURL, "/") { - return c.baseURL + p + if strings.HasSuffix(cli.baseURL, "/") { + return cli.baseURL + p } - return c.baseURL + "/" + p + return cli.baseURL + "/" + p } // Define an error interface so we can get at the underlying status code if it's @@ -156,13 +156,13 @@ func closeResp(r *http.Response) { r.Body.Close() } -func (c *client) get(resource, name string, v interface{}) error { - return c.getResource(c.apiVersion, c.namespace, resource, name, v) +func (cli *client) get(resource, name string, v interface{}) error { + return cli.getResource(cli.apiVersion, cli.namespace, resource, name, v) } -func (c *client) getResource(apiVersion, namespace, resource, name string, v interface{}) error { - url := c.urlFor(apiVersion, namespace, resource, name) - resp, err := c.client.Get(url) +func (cli *client) getResource(apiVersion, namespace, resource, name string, v interface{}) error { + url := cli.urlFor(apiVersion, namespace, resource, name) + resp, err := cli.client.Get(url) if err != nil { return err } @@ -173,22 +173,22 @@ func (c *client) getResource(apiVersion, namespace, resource, name string, v int return json.NewDecoder(resp.Body).Decode(v) } -func (c *client) list(resource string, v interface{}) error { - return c.get(resource, "", v) +func (cli *client) list(resource string, v interface{}) error { + return cli.get(resource, "", v) } -func (c *client) post(resource string, v interface{}) error { - return c.postResource(c.apiVersion, c.namespace, resource, v) +func (cli *client) post(resource string, v interface{}) error { + return cli.postResource(cli.apiVersion, cli.namespace, resource, v) } -func (c *client) postResource(apiVersion, namespace, resource string, v interface{}) error { +func (cli *client) postResource(apiVersion, namespace, resource string, v interface{}) error { body, err := json.Marshal(v) if err != nil { return fmt.Errorf("marshal object: %v", err) } - url := c.urlFor(apiVersion, namespace, resource, "") - resp, err := c.client.Post(url, "application/json", bytes.NewReader(body)) + url := cli.urlFor(apiVersion, namespace, resource, "") + resp, err := cli.client.Post(url, "application/json", bytes.NewReader(body)) if err != nil { return err } @@ -196,13 +196,13 @@ func (c *client) postResource(apiVersion, namespace, resource string, v interfac return checkHTTPErr(resp, http.StatusCreated) } -func (c *client) delete(resource, name string) error { - url := c.urlFor(c.apiVersion, c.namespace, resource, name) +func (cli *client) delete(resource, name string) error { + url := cli.urlFor(cli.apiVersion, cli.namespace, resource, name) req, err := http.NewRequest("DELETE", url, nil) if err != nil { return fmt.Errorf("create delete request: %v", err) } - resp, err := c.client.Do(req) + resp, err := cli.client.Do(req) if err != nil { return fmt.Errorf("delete request: %v", err) } @@ -210,7 +210,7 @@ func (c *client) delete(resource, name string) error { return checkHTTPErr(resp, http.StatusOK) } -func (c *client) deleteAll(resource string) error { +func (cli *client) deleteAll(resource string) error { var list struct { k8sapi.TypeMeta `json:",inline"` k8sapi.ListMeta `json:"metadata,omitempty"` @@ -219,24 +219,24 @@ func (c *client) deleteAll(resource string) error { k8sapi.ObjectMeta `json:"metadata,omitempty"` } `json:"items"` } - if err := c.list(resource, &list); err != nil { + if err := cli.list(resource, &list); err != nil { return err } for _, item := range list.Items { - if err := c.delete(resource, item.Name); err != nil { + if err := cli.delete(resource, item.Name); err != nil { return err } } return nil } -func (c *client) put(resource, name string, v interface{}) error { +func (cli *client) put(resource, name string, v interface{}) error { body, err := json.Marshal(v) if err != nil { return fmt.Errorf("marshal object: %v", err) } - url := c.urlFor(c.apiVersion, c.namespace, resource, name) + url := cli.urlFor(cli.apiVersion, cli.namespace, resource, name) req, err := http.NewRequest("PUT", url, bytes.NewReader(body)) if err != nil { return fmt.Errorf("create patch request: %v", err) @@ -244,7 +244,7 @@ func (c *client) put(resource, name string, v interface{}) error { req.Header.Set("Content-Length", strconv.Itoa(len(body))) - resp, err := c.client.Do(req) + resp, err := cli.client.Do(req) if err != nil { return fmt.Errorf("patch request: %v", err) } From 367b187cf4d529ef57f457c99ae7ad53700e9c19 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 18 Dec 2019 15:51:44 +0100 Subject: [PATCH 66/72] Fix missspell --- .golangci.yml | 1 - connector/github/github.go | 4 ++-- server/handlers.go | 4 ++-- storage/kubernetes/k8sapi/crd_extensions.go | 2 +- storage/sql/config.go | 2 +- 5 files changed, 6 insertions(+), 7 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 5bfe3e99..7ca89f0c 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -16,7 +16,6 @@ linters: - wsl # TODO: fix me - - misspell - unparam - goimports - golint diff --git a/connector/github/github.go b/connector/github/github.go index 6d915edc..d9356e73 100644 --- a/connector/github/github.go +++ b/connector/github/github.go @@ -144,7 +144,7 @@ type githubConnector struct { hostName string // Used to support untrusted/self-signed CA certs. rootCA string - // HTTP Client that trusts the custom delcared rootCA cert. + // HTTP Client that trusts the custom declared rootCA cert. httpClient *http.Client // optional choice between 'name' (default) or 'slug' teamNameField string @@ -206,7 +206,7 @@ func (e *oauth2Error) Error() string { return e.error + ": " + e.errorDescription } -// newHTTPClient returns a new HTTP client that trusts the custom delcared rootCA cert. +// newHTTPClient returns a new HTTP client that trusts the custom declared rootCA cert. func newHTTPClient(rootCA string) (*http.Client, error) { tlsConfig := tls.Config{RootCAs: x509.NewCertPool()} rootCABytes, err := ioutil.ReadFile(rootCA) diff --git a/server/handlers.go b/server/handlers.go index 0f5b0d23..ede474a4 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -45,8 +45,8 @@ func (s *Server) newHealthChecker(ctx context.Context) http.Handler { return h } -// healthChecker periodically performs health checks on server dependenices. -// Currently, it only checks that the storage layer is avialable. +// healthChecker periodically performs health checks on server dependencies. +// Currently, it only checks that the storage layer is available. type healthChecker struct { s *Server diff --git a/storage/kubernetes/k8sapi/crd_extensions.go b/storage/kubernetes/k8sapi/crd_extensions.go index 4b55e393..7a65410b 100644 --- a/storage/kubernetes/k8sapi/crd_extensions.go +++ b/storage/kubernetes/k8sapi/crd_extensions.go @@ -43,7 +43,7 @@ type CustomResourceDefinitionNames struct { ListKind string `json:"listKind,omitempty" protobuf:"bytes,5,opt,name=listKind"` } -// ResourceScope is an enum defining the different scopes availabe to a custom resource +// ResourceScope is an enum defining the different scopes available to a custom resource type ResourceScope string const ( diff --git a/storage/sql/config.go b/storage/sql/config.go index 24467169..827b0df1 100644 --- a/storage/sql/config.go +++ b/storage/sql/config.go @@ -311,7 +311,7 @@ func (s *MySQL) open(logger log.Logger) (*conn, error) { err = db.Ping() if err != nil { if mysqlErr, ok := err.(*mysql.MySQLError); ok && mysqlErr.Number == mysqlErrUnknownSysVar { - logger.Info("reconnecting with MySQL pre-5.7.20 compatibilty mode") + logger.Info("reconnecting with MySQL pre-5.7.20 compatibility mode") // MySQL 5.7.20 introduced transaction_isolation and deprecated tx_isolation. // MySQL 8.0 doesn't have tx_isolation at all. From 9bd5ae519739254ee75baa5f8507b6a18b39bfdf Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 18 Dec 2019 15:53:34 +0100 Subject: [PATCH 67/72] Fix goimports --- .golangci.yml | 1 - cmd/dex/config_test.go | 2 +- connector/google/google.go | 4 ++-- connector/oidc/oidc_test.go | 3 ++- connector/saml/saml.go | 5 +++-- server/server.go | 8 ++++---- 6 files changed, 12 insertions(+), 11 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 7ca89f0c..c658d914 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -17,7 +17,6 @@ linters: # TODO: fix me - unparam - - goimports - golint - whitespace - goconst diff --git a/cmd/dex/config_test.go b/cmd/dex/config_test.go index d7875ad1..87f1a578 100644 --- a/cmd/dex/config_test.go +++ b/cmd/dex/config_test.go @@ -1,7 +1,6 @@ package main import ( - "github.com/dexidp/dex/server" "testing" "github.com/ghodss/yaml" @@ -9,6 +8,7 @@ import ( "github.com/dexidp/dex/connector/mock" "github.com/dexidp/dex/connector/oidc" + "github.com/dexidp/dex/server" "github.com/dexidp/dex/storage" "github.com/dexidp/dex/storage/sql" ) diff --git a/connector/google/google.go b/connector/google/google.go index 7561ca4d..37b6dc15 100644 --- a/connector/google/google.go +++ b/connector/google/google.go @@ -11,12 +11,12 @@ import ( "github.com/coreos/go-oidc" "golang.org/x/oauth2" + "golang.org/x/oauth2/google" + admin "google.golang.org/api/admin/directory/v1" "github.com/dexidp/dex/connector" pkg_groups "github.com/dexidp/dex/pkg/groups" "github.com/dexidp/dex/pkg/log" - "golang.org/x/oauth2/google" - admin "google.golang.org/api/admin/directory/v1" ) const ( diff --git a/connector/oidc/oidc_test.go b/connector/oidc/oidc_test.go index f766a875..22b035c1 100644 --- a/connector/oidc/oidc_test.go +++ b/connector/oidc/oidc_test.go @@ -16,9 +16,10 @@ import ( "testing" "time" - "github.com/dexidp/dex/connector" "github.com/sirupsen/logrus" "gopkg.in/square/go-jose.v2" + + "github.com/dexidp/dex/connector" ) func TestKnownBrokenAuthHeaderProvider(t *testing.T) { diff --git a/connector/saml/saml.go b/connector/saml/saml.go index f4e52a69..70ab413c 100644 --- a/connector/saml/saml.go +++ b/connector/saml/saml.go @@ -14,11 +14,12 @@ import ( "time" "github.com/beevik/etree" + dsig "github.com/russellhaering/goxmldsig" + "github.com/russellhaering/goxmldsig/etreeutils" + "github.com/dexidp/dex/connector" "github.com/dexidp/dex/pkg/groups" "github.com/dexidp/dex/pkg/log" - dsig "github.com/russellhaering/goxmldsig" - "github.com/russellhaering/goxmldsig/etreeutils" ) // nolint diff --git a/server/server.go b/server/server.go index fa860330..4dc7337d 100644 --- a/server/server.go +++ b/server/server.go @@ -14,6 +14,10 @@ import ( "sync/atomic" "time" + "github.com/felixge/httpsnoop" + "github.com/gorilla/handlers" + "github.com/gorilla/mux" + "github.com/prometheus/client_golang/prometheus" "golang.org/x/crypto/bcrypt" "github.com/dexidp/dex/connector" @@ -31,10 +35,6 @@ import ( "github.com/dexidp/dex/connector/saml" "github.com/dexidp/dex/pkg/log" "github.com/dexidp/dex/storage" - "github.com/felixge/httpsnoop" - "github.com/gorilla/handlers" - "github.com/gorilla/mux" - "github.com/prometheus/client_golang/prometheus" ) // LocalConnector is the local passwordDB connector which is an internal From f141f2133b0e9e2ab602d3e41cddf57c0d659b54 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 18 Dec 2019 15:56:12 +0100 Subject: [PATCH 68/72] Fix whitespace --- .golangci.yml | 1 - cmd/dex/config_test.go | 1 - cmd/dex/serve.go | 1 - connector/bitbucketcloud/bitbucketcloud.go | 2 -- connector/bitbucketcloud/bitbucketcloud_test.go | 3 --- connector/github/github.go | 2 -- connector/github/github_test.go | 2 -- connector/gitlab/gitlab_test.go | 4 ---- connector/keystone/keystone.go | 1 - connector/ldap/ldap.go | 2 -- connector/saml/saml.go | 1 - server/api.go | 2 -- server/api_test.go | 2 -- server/handlers.go | 1 - server/handlers_test.go | 1 - server/server_test.go | 3 --- server/templates.go | 1 - storage/conformance/conformance.go | 2 -- storage/sql/crud.go | 1 - 19 files changed, 33 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index c658d914..d0dcfd9b 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -18,7 +18,6 @@ linters: # TODO: fix me - unparam - golint - - whitespace - goconst - unconvert - bodyclose diff --git a/cmd/dex/config_test.go b/cmd/dex/config_test.go index 87f1a578..1df1f809 100644 --- a/cmd/dex/config_test.go +++ b/cmd/dex/config_test.go @@ -211,5 +211,4 @@ logger: if diff := pretty.Compare(c, want); diff != "" { t.Errorf("got!=want: %s", diff) } - } diff --git a/cmd/dex/serve.go b/cmd/dex/serve.go index 7d0e0deb..293d3e66 100644 --- a/cmd/dex/serve.go +++ b/cmd/dex/serve.go @@ -182,7 +182,6 @@ func serve(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to initialize storage connectors: %v", err) } storageConnectors[i] = conn - } if c.EnablePasswordDB { diff --git a/connector/bitbucketcloud/bitbucketcloud.go b/connector/bitbucketcloud/bitbucketcloud.go index 7d58221a..d8ccf2e5 100644 --- a/connector/bitbucketcloud/bitbucketcloud.go +++ b/connector/bitbucketcloud/bitbucketcloud.go @@ -41,7 +41,6 @@ type Config struct { // Open returns a strategy for logging in through Bitbucket. func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) { - b := bitbucketConnector{ redirectURI: c.RedirectURI, teams: c.Teams, @@ -373,7 +372,6 @@ type userTeamsResponse struct { } func (b *bitbucketConnector) userTeams(ctx context.Context, client *http.Client) ([]string, error) { - var teams []string apiURL := b.apiURL + "/teams?role=member" diff --git a/connector/bitbucketcloud/bitbucketcloud_test.go b/connector/bitbucketcloud/bitbucketcloud_test.go index b9f4ba08..488c7886 100644 --- a/connector/bitbucketcloud/bitbucketcloud_test.go +++ b/connector/bitbucketcloud/bitbucketcloud_test.go @@ -14,7 +14,6 @@ import ( ) func TestUserGroups(t *testing.T) { - teamsResponse := userTeamsResponse{ pagedResponse: pagedResponse{ Size: 3, @@ -46,7 +45,6 @@ func TestUserGroups(t *testing.T) { } func TestUserWithoutTeams(t *testing.T) { - s := newTestServer(map[string]interface{}{ "/teams?role=member": userTeamsResponse{}, }) @@ -61,7 +59,6 @@ func TestUserWithoutTeams(t *testing.T) { } func TestUsernameIncludedInFederatedIdentity(t *testing.T) { - s := newTestServer(map[string]interface{}{ "/user": user{Username: "some-login"}, "/user/emails": userEmailResponse{ diff --git a/connector/github/github.go b/connector/github/github.go index d9356e73..41aaf589 100644 --- a/connector/github/github.go +++ b/connector/github/github.go @@ -67,7 +67,6 @@ type Org struct { // Open returns a strategy for logging in through GitHub. func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) { - if c.Org != "" { // Return error if both 'org' and 'orgs' fields are used. if len(c.Orgs) > 0 { @@ -107,7 +106,6 @@ func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) if g.httpClient, err = newHTTPClient(g.rootCA); err != nil { return nil, fmt.Errorf("failed to create HTTP client: %v", err) } - } g.loadAllGroups = c.LoadAllGroups diff --git a/connector/github/github_test.go b/connector/github/github_test.go index 539a2e69..76d7463c 100644 --- a/connector/github/github_test.go +++ b/connector/github/github_test.go @@ -126,7 +126,6 @@ func TestUserGroupsWithTeamNameAndSlugFieldConfig(t *testing.T) { // tests that the users login is used as their username when they have no username set func TestUsernameIncludedInFederatedIdentity(t *testing.T) { - s := newTestServer(map[string]testResponse{ "/user": {data: user{Login: "some-login", ID: 12345678}}, "/user/emails": {data: []userEmail{{ @@ -168,7 +167,6 @@ func TestUsernameIncludedInFederatedIdentity(t *testing.T) { } func TestLoginUsedAsIDWhenConfigured(t *testing.T) { - s := newTestServer(map[string]testResponse{ "/user": {data: user{Login: "some-login", ID: 12345678, Name: "Joe Bloggs"}}, "/user/emails": {data: []userEmail{{ diff --git a/connector/gitlab/gitlab_test.go b/connector/gitlab/gitlab_test.go index 331b486e..23cf9aac 100644 --- a/connector/gitlab/gitlab_test.go +++ b/connector/gitlab/gitlab_test.go @@ -65,7 +65,6 @@ func TestUserGroupsWithoutOrgs(t *testing.T) { // tests that the email is used as their username when they have no username set func TestUsernameIncludedInFederatedIdentity(t *testing.T) { - s := newTestServer(map[string]interface{}{ "/api/v4/user": gitlabUser{Email: "some@email.com", ID: 12345678}, "/oauth/token": map[string]interface{}{ @@ -102,7 +101,6 @@ func TestUsernameIncludedInFederatedIdentity(t *testing.T) { } func TestLoginUsedAsIDWhenConfigured(t *testing.T) { - s := newTestServer(map[string]interface{}{ "/api/v4/user": gitlabUser{Email: "some@email.com", ID: 12345678, Name: "Joe Bloggs", Username: "joebloggs"}, "/oauth/token": map[string]interface{}{ @@ -130,7 +128,6 @@ func TestLoginUsedAsIDWhenConfigured(t *testing.T) { } func TestLoginWithTeamWhitelisted(t *testing.T) { - s := newTestServer(map[string]interface{}{ "/api/v4/user": gitlabUser{Email: "some@email.com", ID: 12345678, Name: "Joe Bloggs"}, "/oauth/token": map[string]interface{}{ @@ -158,7 +155,6 @@ func TestLoginWithTeamWhitelisted(t *testing.T) { } func TestLoginWithTeamNonWhitelisted(t *testing.T) { - s := newTestServer(map[string]interface{}{ "/api/v4/user": gitlabUser{Email: "some@email.com", ID: 12345678, Name: "Joe Bloggs", Username: "joebloggs"}, "/oauth/token": map[string]interface{}{ diff --git a/connector/keystone/keystone.go b/connector/keystone/keystone.go index dc74a01f..71a59de8 100644 --- a/connector/keystone/keystone.go +++ b/connector/keystone/keystone.go @@ -150,7 +150,6 @@ func (p *conn) Prompt() string { return "username" } func (p *conn) Refresh( ctx context.Context, scopes connector.Scopes, identity connector.Identity) (connector.Identity, error) { - token, err := p.getAdminToken(ctx) if err != nil { return identity, fmt.Errorf("keystone: failed to obtain admin token: %v", err) diff --git a/connector/ldap/ldap.go b/connector/ldap/ldap.go index aed73194..cac3539f 100644 --- a/connector/ldap/ldap.go +++ b/connector/ldap/ldap.go @@ -189,7 +189,6 @@ func (c *Config) OpenConnector(logger log.Logger) (interface { } func (c *Config) openConnector(logger log.Logger) (*ldapConnector, error) { - requiredFields := []struct { name string val string @@ -365,7 +364,6 @@ func (c *ldapConnector) identityFromEntry(user ldap.Entry) (ident connector.Iden } func (c *ldapConnector) userEntry(conn *ldap.Conn, username string) (user ldap.Entry, found bool, err error) { - filter := fmt.Sprintf("(%s=%s)", c.UserSearch.Username, ldap.EscapeFilter(username)) if c.UserSearch.Filter != "" { filter = fmt.Sprintf("(&%s%s)", c.UserSearch.Filter, filter) diff --git a/connector/saml/saml.go b/connector/saml/saml.go index 70ab413c..1c1cb460 100644 --- a/connector/saml/saml.go +++ b/connector/saml/saml.go @@ -249,7 +249,6 @@ type provider struct { } func (p *provider) POSTData(s connector.Scopes, id string) (action, value string, err error) { - r := &authnRequest{ ProtocolBinding: bindingPOST, ID: id, diff --git a/server/api.go b/server/api.go index 9feb0e9a..55784b90 100644 --- a/server/api.go +++ b/server/api.go @@ -218,7 +218,6 @@ func (d dexAPI) DeletePassword(ctx context.Context, req *api.DeletePasswordReq) return nil, fmt.Errorf("delete password: %v", err) } return &api.DeletePasswordResp{}, nil - } func (d dexAPI) GetVersion(ctx context.Context, req *api.VersionReq) (*api.VersionResp, error) { @@ -248,7 +247,6 @@ func (d dexAPI) ListPasswords(ctx context.Context, req *api.ListPasswordReq) (*a return &api.ListPasswordResp{ Passwords: passwords, }, nil - } func (d dexAPI) VerifyPassword(ctx context.Context, req *api.VerifyPasswordReq) (*api.VerifyPasswordResp, error) { diff --git a/server/api_test.go b/server/api_test.go index 80a22486..511d5d39 100644 --- a/server/api_test.go +++ b/server/api_test.go @@ -167,7 +167,6 @@ func TestPassword(t *testing.T) { if _, err := client.DeletePassword(ctx, &deleteReq); err != nil { t.Fatalf("Unable to delete password: %v", err) } - } // Ensures checkCost returns expected values @@ -495,7 +494,6 @@ func TestUpdateClient(t *testing.T) { if tc.cleanup != nil { tc.cleanup(t, tc.req.Id) } - }) } } diff --git a/server/handlers.go b/server/handlers.go index ede474a4..97a46d57 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -922,7 +922,6 @@ func (s *Server) handleAuthCode(w http.ResponseWriter, r *http.Request, client s deleteToken = true return } - } } s.writeAccessToken(w, idToken, accessToken, refreshToken, expiry) diff --git a/server/handlers_test.go b/server/handlers_test.go index 395b7e72..b30076dd 100644 --- a/server/handlers_test.go +++ b/server/handlers_test.go @@ -24,7 +24,6 @@ func TestHandleHealth(t *testing.T) { if rr.Code != http.StatusOK { t.Errorf("expected 200 got %d", rr.Code) } - } type badStorage struct { diff --git a/server/server_test.go b/server/server_test.go index 6759f240..ef49ed6f 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -799,7 +799,6 @@ func TestCrossClientScopes(t *testing.T) { if !reflect.DeepEqual(idToken.Audience, expAudience) { t.Errorf("expected audience %q, got %q", expAudience, idToken.Audience) } - } if gotState := q.Get("state"); gotState != state { t.Errorf("state did not match, want=%q got=%q", state, gotState) @@ -921,7 +920,6 @@ func TestCrossClientScopesWithAzpInAudienceByDefault(t *testing.T) { if !reflect.DeepEqual(idToken.Audience, expAudience) { t.Errorf("expected audience %q, got %q", expAudience, idToken.Audience) } - } if gotState := q.Get("state"); gotState != state { t.Errorf("state did not match, want=%q got=%q", state, gotState) @@ -1058,7 +1056,6 @@ func TestPasswordDB(t *testing.T) { t.Errorf("%s: %s", tc.name, diff) } } - } func TestPasswordDBUsernamePrompt(t *testing.T) { diff --git a/server/templates.go b/server/templates.go index 13dda8f1..ac0957af 100644 --- a/server/templates.go +++ b/server/templates.go @@ -176,7 +176,6 @@ func loadTemplates(c webConfig, templatesDir string) (*templates, error) { //assetPath is static/main.css //relativeURL("/dex", "/dex/auth", "static/main.css") = "../static/main.css" func relativeURL(serverPath, reqPath, assetPath string) string { - splitPath := func(p string) []string { res := []string{} parts := strings.Split(path.Clean(p), "/") diff --git a/storage/conformance/conformance.go b/storage/conformance/conformance.go index 9832a7d8..92a48d6a 100644 --- a/storage/conformance/conformance.go +++ b/storage/conformance/conformance.go @@ -160,7 +160,6 @@ func testAuthRequestCRUD(t *testing.T, s storage.Storage) { if err := s.DeleteAuthRequest(a2.ID); err != nil { t.Fatalf("failed to delete auth request: %v", err) } - } func testAuthCodeCRUD(t *testing.T, s storage.Storage) { @@ -509,7 +508,6 @@ func testPasswordCRUD(t *testing.T, s storage.Storage) { _, err = s.GetPassword(password1.Email) mustBeErrNotFound(t, "password", err) - } func testOfflineSessionCRUD(t *testing.T, s storage.Storage) { diff --git a/storage/sql/crud.go b/storage/sql/crud.go index e96a7b12..e87dc56a 100644 --- a/storage/sql/crud.go +++ b/storage/sql/crud.go @@ -169,7 +169,6 @@ func (c *conn) UpdateAuthRequest(id string, updater func(a storage.AuthRequest) } return nil }) - } func (c *conn) GetAuthRequest(id string) (storage.AuthRequest, error) { From 2f8d1f8e42eebe6b4a4b421cc97053dcdb6b7b4c Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 18 Dec 2019 15:56:46 +0100 Subject: [PATCH 69/72] Fix unconvert --- .golangci.yml | 1 - connector/keystone/keystone_test.go | 2 +- storage/etcd/etcd.go | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index d0dcfd9b..89e09982 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -19,7 +19,6 @@ linters: - unparam - golint - goconst - - unconvert - bodyclose - staticcheck - nakedret diff --git a/connector/keystone/keystone_test.go b/connector/keystone/keystone_test.go index d5d65ef1..d8bb0268 100644 --- a/connector/keystone/keystone_test.go +++ b/connector/keystone/keystone_test.go @@ -274,7 +274,7 @@ func TestUseRefreshToken(t *testing.T) { delete(t, token, groupID, groupsURL) expectEquals(t, 1, len(identityRefresh.Groups)) - expectEquals(t, testGroup, string(identityRefresh.Groups[0])) + expectEquals(t, testGroup, identityRefresh.Groups[0]) } func TestUseRefreshTokenUserDeleted(t *testing.T) { diff --git a/storage/etcd/etcd.go b/storage/etcd/etcd.go index d106f443..ee588129 100644 --- a/storage/etcd/etcd.go +++ b/storage/etcd/etcd.go @@ -156,7 +156,7 @@ func (c *conn) UpdateRefreshToken(id string, updater func(old storage.RefreshTok return c.txnUpdate(ctx, keyID(refreshTokenPrefix, id), func(currentValue []byte) ([]byte, error) { var current RefreshToken if len(currentValue) > 0 { - if err := json.Unmarshal([]byte(currentValue), ¤t); err != nil { + if err := json.Unmarshal(currentValue, ¤t); err != nil { return nil, err } } From 65c77e9db2e1e32fe4837970ea2da06758be42da Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 18 Dec 2019 16:04:03 +0100 Subject: [PATCH 70/72] Fix bodyclose --- .golangci.yml | 1 - connector/keystone/keystone.go | 3 +++ connector/keystone/keystone_test.go | 15 +++++++++++++-- server/server_test.go | 16 ++++++++++++++-- 4 files changed, 30 insertions(+), 5 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 89e09982..1ff5dd64 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -19,7 +19,6 @@ linters: - unparam - golint - goconst - - bodyclose - staticcheck - nakedret - ineffassign diff --git a/connector/keystone/keystone.go b/connector/keystone/keystone.go index 71a59de8..6ce22d1a 100644 --- a/connector/keystone/keystone.go +++ b/connector/keystone/keystone.go @@ -209,6 +209,8 @@ func (p *conn) getAdminToken(ctx context.Context) (string, error) { if err != nil { return "", err } + defer resp.Body.Close() + token := resp.Header.Get("X-Subject-Token") return token, nil } @@ -228,6 +230,7 @@ func (p *conn) checkIfUserExists(ctx context.Context, userID string, token strin if err != nil { return false, err } + defer resp.Body.Close() if resp.StatusCode == 200 { return true, nil diff --git a/connector/keystone/keystone_test.go b/connector/keystone/keystone_test.go index d8bb0268..784cdc4f 100644 --- a/connector/keystone/keystone_test.go +++ b/connector/keystone/keystone_test.go @@ -154,7 +154,12 @@ func delete(t *testing.T, token, id, uri string) { t.Fatalf("error: %v", err) } req.Header.Set("X-Auth-Token", token) - client.Do(req) + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("error: %v", err) + } + defer resp.Body.Close() } func createGroup(t *testing.T, token, description, name string) string { @@ -208,7 +213,13 @@ func addUserToGroup(t *testing.T, token, groupID, userID string) error { return err } req.Header.Set("X-Auth-Token", token) - client.Do(req) + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("error: %v", err) + } + defer resp.Body.Close() + return nil } diff --git a/server/server_test.go b/server/server_test.go index ef49ed6f..8fe84c9a 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -590,6 +590,8 @@ func TestOAuth2CodeFlow(t *testing.T) { if err != nil { t.Fatalf("get failed: %v", err) } + defer resp.Body.Close() + if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil { t.Fatal(err) } @@ -726,6 +728,8 @@ func TestOAuth2ImplicitFlow(t *testing.T) { if err != nil { t.Fatalf("get failed: %v", err) } + defer resp.Body.Close() + if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil { t.Fatal(err) } @@ -847,6 +851,8 @@ func TestCrossClientScopes(t *testing.T) { if err != nil { t.Fatalf("get failed: %v", err) } + defer resp.Body.Close() + if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil { t.Fatal(err) } @@ -967,6 +973,8 @@ func TestCrossClientScopesWithAzpInAudienceByDefault(t *testing.T) { if err != nil { t.Fatalf("get failed: %v", err) } + defer resp.Body.Close() + if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil { t.Fatal(err) } @@ -1222,9 +1230,11 @@ func TestRefreshTokenFlow(t *testing.T) { RedirectURL: redirectURL, } - if _, err = http.Get(oauth2Client.server.URL + "/login"); err != nil { + resp, err := http.Get(oauth2Client.server.URL + "/login") + if err != nil { t.Fatalf("get failed: %v", err) } + defer resp.Body.Close() tok := &oauth2.Token{ RefreshToken: oauth2Client.token.RefreshToken, @@ -1232,9 +1242,11 @@ func TestRefreshTokenFlow(t *testing.T) { } // Login in again to receive a new token. - if _, err = http.Get(oauth2Client.server.URL + "/login"); err != nil { + resp, err = http.Get(oauth2Client.server.URL + "/login") + if err != nil { t.Fatalf("get failed: %v", err) } + defer resp.Body.Close() // try to refresh expired token with old refresh token. if _, err := oauth2Client.config.TokenSource(ctx, tok).Token(); err == nil { From 050d5af937626f5e1403aabff60ff07941dbc8a3 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 18 Dec 2019 16:07:06 +0100 Subject: [PATCH 71/72] Fix ineffassign --- .golangci.yml | 1 - server/templates.go | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.golangci.yml b/.golangci.yml index 1ff5dd64..16d82a5e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -21,7 +21,6 @@ linters: - goconst - staticcheck - nakedret - - ineffassign - errcheck - gosec - gochecknoinits diff --git a/server/templates.go b/server/templates.go index ac0957af..b9beab33 100644 --- a/server/templates.go +++ b/server/templates.go @@ -206,6 +206,7 @@ func relativeURL(serverPath, reqPath, assetPath string) string { server, req, asset := splitPath(serverPath), splitPath(reqPath), splitPath(assetPath) // Remove common prefix of request path with server path + // nolint: ineffassign server, req = stripCommonParts(server, req) // Remove common prefix of request path with asset path From 8e0ae820340f40593c497d155c27e2211f948df4 Mon Sep 17 00:00:00 2001 From: Lars Lehtonen Date: Fri, 15 Nov 2019 16:31:22 -0800 Subject: [PATCH 72/72] connector/oidc: replace deprecated oauth2.RegisterBrokenAuthHeaderProvider with oauth2.Endpoint.AuthStyle --- connector/oidc/oidc.go | 21 +++++---------------- connector/oidc/oidc_test.go | 2 ++ 2 files changed, 7 insertions(+), 16 deletions(-) diff --git a/connector/oidc/oidc.go b/connector/oidc/oidc.go index 341e4e0a..2c199112 100644 --- a/connector/oidc/oidc.go +++ b/connector/oidc/oidc.go @@ -9,7 +9,6 @@ import ( "net/http" "net/url" "strings" - "sync" "time" "github.com/coreos/go-oidc" @@ -85,18 +84,6 @@ func knownBrokenAuthHeaderProvider(issuerURL string) bool { return false } -// golang.org/x/oauth2 doesn't do internal locking. Need to do it in this -// package ourselves and hope that other packages aren't calling it at the -// same time. -var registerMu = new(sync.Mutex) - -func registerBrokenAuthHeaderProvider(url string) { - registerMu.Lock() - defer registerMu.Unlock() - - oauth2.RegisterBrokenAuthHeaderProvider(url) -} - // Open returns a connector which can be used to login users through an upstream // OpenID Connect provider. func (c *Config) Open(id string, logger log.Logger) (conn connector.Connector, err error) { @@ -108,13 +95,15 @@ func (c *Config) Open(id string, logger log.Logger) (conn connector.Connector, e return nil, fmt.Errorf("failed to get provider: %v", err) } + endpoint := provider.Endpoint() + if c.BasicAuthUnsupported != nil { // Setting "basicAuthUnsupported" always overrides our detection. if *c.BasicAuthUnsupported { - registerBrokenAuthHeaderProvider(provider.Endpoint().TokenURL) + endpoint.AuthStyle = oauth2.AuthStyleInParams } } else if knownBrokenAuthHeaderProvider(c.Issuer) { - registerBrokenAuthHeaderProvider(provider.Endpoint().TokenURL) + endpoint.AuthStyle = oauth2.AuthStyleInParams } scopes := []string{oidc.ScopeOpenID} @@ -131,7 +120,7 @@ func (c *Config) Open(id string, logger log.Logger) (conn connector.Connector, e oauth2Config: &oauth2.Config{ ClientID: clientID, ClientSecret: c.ClientSecret, - Endpoint: provider.Endpoint(), + Endpoint: endpoint, Scopes: scopes, RedirectURL: c.RedirectURI, }, diff --git a/connector/oidc/oidc_test.go b/connector/oidc/oidc_test.go index f766a875..f5f53e6b 100644 --- a/connector/oidc/oidc_test.go +++ b/connector/oidc/oidc_test.go @@ -111,6 +111,7 @@ func TestHandleCallback(t *testing.T) { } defer testServer.Close() serverURL := testServer.URL + basicAuth := true config := Config{ Issuer: serverURL, ClientID: "clientID", @@ -120,6 +121,7 @@ func TestHandleCallback(t *testing.T) { UserIDKey: tc.userIDKey, UserNameKey: tc.userNameKey, InsecureSkipEmailVerified: tc.insecureSkipEmailVerified, + BasicAuthUnsupported: &basicAuth, } conn, err := newConnector(config)