Skip to content

Commit

Permalink
Merge pull request #10801 from MUzairS15/MUzairS15/conneciton-by-id
Browse files Browse the repository at this point in the history
[Server] Add support to fetch connection by id.
  • Loading branch information
leecalcote committed May 1, 2024
2 parents 3ebc6f7 + 3e01be1 commit 7c23edb
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 19 deletions.
13 changes: 6 additions & 7 deletions server/handlers/grafana_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ func (h *Handler) GrafanaPingHandler(w http.ResponseWriter, req *http.Request, p
token, _ := req.Context().Value(models.TokenCtxKey).(string)
connectionID := uuid.FromStringOrNil(mux.Vars(req)["connectionID"])

connection, statusCode, err := p.GetConnectionByID(token, connectionID, "grafana")
connection, statusCode, err := p.GetConnectionByIDAndKind(token, connectionID, "grafana")
if err != nil {
http.Error(w, err.Error(), statusCode)
return
Expand Down Expand Up @@ -182,8 +182,8 @@ func (h *Handler) GrafanaBoardsHandler(w http.ResponseWriter, req *http.Request,
}
token, _ := req.Context().Value(models.TokenCtxKey).(string)
connectionID := uuid.FromStringOrNil(mux.Vars(req)["connectionID"])
connection, statusCode, err := p.GetConnectionByID(token, connectionID, "grafana")
fmt.Println("CONNECTION ID : ", connectionID)
connection, statusCode, err := p.GetConnectionByIDAndKind(token, connectionID, "grafana")
h.log.Debug("connection id : ", connectionID)
if err != nil {
h.log.Error(err)
http.Error(w, err.Error(), statusCode)
Expand All @@ -198,7 +198,6 @@ func (h *Handler) GrafanaBoardsHandler(w http.ResponseWriter, req *http.Request,
return
}
apiKeyOrBasicAuth, _ := cred.Secret["secret"].(string)
fmt.Println(apiKeyOrBasicAuth, "GRAFANA KEY", cred.Secret)
if err := h.config.GrafanaClient.Validate(req.Context(), url, apiKeyOrBasicAuth); err != nil {
h.log.Error(models.ErrGrafanaScan(err))
http.Error(w, models.ErrGrafanaScan(err).Error(), http.StatusInternalServerError)
Expand Down Expand Up @@ -234,7 +233,7 @@ func (h *Handler) GrafanaQueryHandler(w http.ResponseWriter, req *http.Request,
reqQuery := req.URL.Query()
token, _ := req.Context().Value(models.TokenCtxKey).(string)
connectionID := uuid.FromStringOrNil(mux.Vars(req)["connectionID"])
connection, statusCode, err := p.GetConnectionByID(token, connectionID, "grafana")
connection, statusCode, err := p.GetConnectionByIDAndKind(token, connectionID, "grafana")
if err != nil {
http.Error(w, err.Error(), statusCode)
return
Expand Down Expand Up @@ -268,7 +267,7 @@ func (h *Handler) GrafanaQueryRangeHandler(w http.ResponseWriter, req *http.Requ

token, _ := req.Context().Value(models.TokenCtxKey).(string)
connectionID := uuid.FromStringOrNil(mux.Vars(req)["connectionID"])
connection, statusCode, err := provider.GetConnectionByID(token, connectionID, "grafana")
connection, statusCode, err := provider.GetConnectionByIDAndKind(token, connectionID, "grafana")
if err != nil {
http.Error(w, err.Error(), statusCode)
return
Expand Down Expand Up @@ -330,7 +329,7 @@ func (h *Handler) SaveSelectedGrafanaBoardsHandler(w http.ResponseWriter, req *h

token, _ := req.Context().Value(models.TokenCtxKey).(string)
connectionID := uuid.FromStringOrNil(mux.Vars(req)["connectionID"])
connection, statusCode, err := p.GetConnectionByID(token, connectionID, "grafana")
connection, statusCode, err := p.GetConnectionByIDAndKind(token, connectionID, "grafana")
if err != nil {
http.Error(w, err.Error(), statusCode)
return
Expand Down
10 changes: 5 additions & 5 deletions server/handlers/prometheus_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ func (h *Handler) PrometheusPingHandler(w http.ResponseWriter, req *http.Request
token, _ := req.Context().Value(models.TokenCtxKey).(string)
connectionID := uuid.FromStringOrNil(mux.Vars(req)["connectionID"])

connection, statusCode, err := p.GetConnectionByID(token, connectionID, "prometheus")
connection, statusCode, err := p.GetConnectionByIDAndKind(token, connectionID, "prometheus")
if err != nil {
http.Error(w, err.Error(), statusCode)
return
Expand Down Expand Up @@ -358,7 +358,7 @@ func (h *Handler) PrometheusQueryHandler(w http.ResponseWriter, req *http.Reques
token, _ := req.Context().Value(models.TokenCtxKey).(string)
connectionID := uuid.FromStringOrNil(mux.Vars(req)["connectionID"])

connection, statusCode, err := p.GetConnectionByID(token, connectionID, "prometheus")
connection, statusCode, err := p.GetConnectionByIDAndKind(token, connectionID, "prometheus")
if err != nil {
http.Error(w, err.Error(), statusCode)
return
Expand All @@ -382,7 +382,7 @@ func (h *Handler) PrometheusQueryRangeHandler(w http.ResponseWriter, req *http.R
token, _ := req.Context().Value(models.TokenCtxKey).(string)
connectionID := uuid.FromStringOrNil(mux.Vars(req)["connectionID"])

connection, statusCode, err := provider.GetConnectionByID(token, connectionID, "prometheus")
connection, statusCode, err := provider.GetConnectionByIDAndKind(token, connectionID, "prometheus")
if err != nil {
http.Error(w, err.Error(), statusCode)
return
Expand Down Expand Up @@ -418,7 +418,7 @@ func (h *Handler) PrometheusStaticBoardHandler(w http.ResponseWriter, req *http.
token, _ := req.Context().Value(models.TokenCtxKey).(string)
connectionID := uuid.FromStringOrNil(mux.Vars(req)["connectionID"])

connection, statusCode, err := provider.GetConnectionByID(token, connectionID, "prometheus")
connection, statusCode, err := provider.GetConnectionByIDAndKind(token, connectionID, "prometheus")
if err != nil {
http.Error(w, err.Error(), statusCode)
return
Expand Down Expand Up @@ -497,7 +497,7 @@ func (h *Handler) SaveSelectedPrometheusBoardsHandler(w http.ResponseWriter, req

token, _ := req.Context().Value(models.TokenCtxKey).(string)
connectionID := uuid.FromStringOrNil(mux.Vars(req)["connectionID"])
connection, statusCode, err := provider.GetConnectionByID(token, connectionID, "prometheus")
connection, statusCode, err := provider.GetConnectionByIDAndKind(token, connectionID, "prometheus")
if err != nil {
http.Error(w, err.Error(), statusCode)
return
Expand Down
2 changes: 1 addition & 1 deletion server/helpers/component_info.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "meshery-server",
"type": "component",
"next_error_code": 1321
"next_error_code": 1322
}
15 changes: 14 additions & 1 deletion server/models/default_local_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -984,10 +984,23 @@ func (l *DefaultLocalProvider) SaveConnection(_ *ConnectionPayload, _ string, _
func (l *DefaultLocalProvider) GetConnections(_ *http.Request, _ string, _, _ int, _, _ string, _ string, _ []string, _ []string) (*connections.ConnectionPage, error) {
return nil, ErrLocalProviderSupport
}
func (l *DefaultLocalProvider) GetConnectionByID(token string, connectionID uuid.UUID, kind string) (*connections.Connection, int, error) {

func (l *DefaultLocalProvider) GetConnectionByIDAndKind(token string, connectionID uuid.UUID, kind string) (*connections.Connection, int, error) {
return nil, http.StatusForbidden, ErrLocalProviderSupport
}

func (l *DefaultLocalProvider) GetConnectionByID(token string, connectionID uuid.UUID) (*connections.Connection, int, error) {
result := connections.Connection{}
err := l.DB.Model(&result).Where("id = ?", connectionID).First(&result).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, http.StatusNotFound, ErrResultNotFound(err)
}
return nil, http.StatusInternalServerError, ErrDBRead(err)
}
return &result, http.StatusOK, err
}

func (l *DefaultLocalProvider) GetConnectionsByKind(_ *http.Request, _ string, _, _ int, _, _, _ string) (*map[string]interface{}, error) {
return nil, ErrLocalProviderSupport
}
Expand Down
5 changes: 5 additions & 0 deletions server/models/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ const (
ErrPrometheusScanCode = "meshery-server-1310"
ErrGrafanaScanCode = "meshery-server-1311"
ErrDBCreateCode = "meshery-server-1312"
ErrDoRequestCode = "meshery-server-1321"
)

var (
Expand Down Expand Up @@ -406,3 +407,7 @@ func ErrPrometheusScan(err error) error {
func ErrDBCreate(err error) error {
return errors.New(ErrDBCreateCode, errors.Alert, []string{"Unable to create record"}, []string{err.Error()}, []string{"Record already exist", "Database connection is not reachable"}, []string{"Delete the record or try updating the record instead of recreating", "Rest the database connection"})
}

func ErrDoRequest(err error, method, endpoint string) error {
return errors.New(ErrDoRequestCode, errors.Alert, []string{fmt.Sprintf("unable to make %s request to %s", method, endpoint)}, []string{err.Error()}, []string{"Requested resource is not reachable.", "Unable to instantiate TCP connection"}, []string{"Ensure correct URL is specified", "Ensure network connectivity to the resource from your network"})
}
3 changes: 2 additions & 1 deletion server/models/providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,8 @@ type Provider interface {

SaveConnection(conn *ConnectionPayload, token string, skipTokenCheck bool) (*connections.Connection, error)
GetConnections(req *http.Request, userID string, page, pageSize int, search, order string, filter string, status []string, kind []string) (*connections.ConnectionPage, error)
GetConnectionByID(token string, connectionID uuid.UUID, kind string) (*connections.Connection, int, error)
GetConnectionByIDAndKind(token string, connectionID uuid.UUID, kind string) (*connections.Connection, int, error)
GetConnectionByID(token string, connectionID uuid.UUID) (*connections.Connection, int, error)
GetConnectionsByKind(req *http.Request, userID string, page, pageSize int, search, order, connectionKind string) (*map[string]interface{}, error)
GetConnectionsStatus(req *http.Request, userID string) (*connections.ConnectionsStatusPage, error)
UpdateConnection(req *http.Request, conn *connections.Connection) (*connections.Connection, error)
Expand Down
10 changes: 7 additions & 3 deletions server/models/remote_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func SafeClose(co io.Closer) {
func (l *RemoteProvider) DoRequest(req *http.Request, tokenString string) (*http.Response, error) {
resp, err := l.doRequestHelper(req, tokenString)
if err != nil {
return nil, ErrTokenRefresh(err)
return nil, ErrDoRequest(err, req.Method, req.URL.String())
}

if resp.StatusCode == 401 {
Expand All @@ -44,11 +44,15 @@ func (l *RemoteProvider) DoRequest(req *http.Request, tokenString string) (*http
resp.Body.Close()
logrus.Warn("trying after refresh")
newToken, err := l.refreshToken(tokenString)
logrus.Info("token refresh successful")
if err != nil {
return nil, ErrTokenRefresh(err)
}
return l.doRequestHelper(req, newToken)
l.Log.Info("token refresh successful")
resp, err := l.doRequestHelper(req, newToken)
if err != nil {
return nil, ErrDoRequest(err, req.Method, req.URL.String())
}
return resp, nil
}
return resp, err
}
Expand Down
40 changes: 39 additions & 1 deletion server/models/remote_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -3796,7 +3796,7 @@ func (l *RemoteProvider) GetConnectionsByKind(req *http.Request, _ string, page,
return &res, nil
}

func (l *RemoteProvider) GetConnectionByID(token string, connectionID uuid.UUID, kind string) (*connections.Connection, int, error) {
func (l *RemoteProvider) GetConnectionByIDAndKind(token string, connectionID uuid.UUID, kind string) (*connections.Connection, int, error) {
if !l.Capabilities.IsSupported(PersistConnection) {
logrus.Error("operation not available")
return nil, http.StatusForbidden, ErrInvalidCapability("PersistConnection", l.ProviderName)
Expand Down Expand Up @@ -3836,6 +3836,44 @@ func (l *RemoteProvider) GetConnectionByID(token string, connectionID uuid.UUID,
return nil, resp.StatusCode, ErrFetch(fmt.Errorf("unable to retrieve connection with id %s", connectionID), "connection", resp.StatusCode)
}

func (l *RemoteProvider) GetConnectionByID(token string, connectionID uuid.UUID) (*connections.Connection, int, error) {
if !l.Capabilities.IsSupported(PersistConnection) {
l.Log.Error(ErrInvalidCapability("PersistConnection", l.ProviderName))
return nil, http.StatusForbidden, ErrInvalidCapability("PersistConnection", l.ProviderName)
}
ep, _ := l.Capabilities.GetEndpointForFeature(PersistConnection)

remoteProviderURL, _ := url.Parse(fmt.Sprintf("%s%s/%s", l.RemoteProviderURL, ep, connectionID))

cReq, _ := http.NewRequest(http.MethodGet, remoteProviderURL.String(), nil)

resp, err := l.DoRequest(cReq, token)
if err != nil {
l.Log.Error(err)
statusCode := http.StatusInternalServerError
return nil, statusCode, ErrFetch(err, "connection", statusCode)
}

if resp.StatusCode == http.StatusOK {
defer func() {
_ = resp.Body.Close()
}()

bdr, err := io.ReadAll(resp.Body)
if err != nil {
return nil, resp.StatusCode, ErrFetch(fmt.Errorf("unable to retrieve connection with id %s", connectionID), "connection", resp.StatusCode)
}
var conn connections.Connection
if err = json.Unmarshal(bdr, &conn); err != nil {
l.Log.Error(ErrUnmarshal(err, "connection"))
return nil, http.StatusInternalServerError, ErrFetch(fmt.Errorf("unable to retrieve connection with id %s", connectionID), "connection", resp.StatusCode)
}
return &conn, resp.StatusCode, nil
}

return nil, resp.StatusCode, ErrFetch(fmt.Errorf("unable to retrieve connection with id %s", connectionID), "connection", resp.StatusCode)
}

func (l *RemoteProvider) GetConnectionsStatus(req *http.Request, userID string) (*connections.ConnectionsStatusPage, error) {
if !l.Capabilities.IsSupported(PersistConnection) {
logrus.Error("operation not available")
Expand Down

0 comments on commit 7c23edb

Please sign in to comment.