View Javadoc
1   /*
2    * Copyright (c) 2002-2021, City of Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.plugins.grafana.service;
35  
36  import fr.paris.lutece.plugins.grafana.business.Dashboard;
37  import fr.paris.lutece.plugins.grafana.business.DashboardHome;
38  import fr.paris.lutece.plugins.grafana.utils.constants.GrafanaConstants;
39  import fr.paris.lutece.portal.business.rbac.RBACHome;
40  import fr.paris.lutece.portal.business.user.AdminUser;
41  import fr.paris.lutece.portal.service.admin.AdminUserService;
42  import fr.paris.lutece.portal.service.rbac.RBACService;
43  import fr.paris.lutece.portal.service.util.AppLogService;
44  import fr.paris.lutece.portal.service.util.AppPropertiesService;
45  import fr.paris.lutece.util.httpaccess.HttpAccess;
46  import fr.paris.lutece.util.httpaccess.HttpAccessException;
47  import fr.paris.lutece.util.signrequest.BasicAuthorizationAuthenticator;
48  import fr.paris.lutece.util.signrequest.RequestAuthenticator;
49  import fr.paris.lutece.util.string.StringUtil;
50  
51  import java.util.ArrayList;
52  import java.util.HashMap;
53  import java.util.List;
54  import java.util.Map;
55  import javax.servlet.http.HttpServletRequest;
56  
57  import org.json.JSONArray;
58  import org.json.JSONObject;
59  
60  /**
61   * DashboardService
62   */
63  public class DashboardService
64  {
65      private static final String NOT_FOUND = "404";
66      private static final String PROPERTY_GRAFANA_SERVER_URL = "grafana.url";
67      private static final String GRAFANA_DASHBOARD_LIST_URL = "/api/search?query=%";
68      private static final String PROPERTY_GRAFANA_SERVER_LOGIN = "grafana.admin.login";
69      private static final String PROPERTY_GRAFANA_SERVER_PWD = "grafana.admin.pwd";
70      private static final String PROPERTY_GRAFANA_SERVER_USER_LOGIN = "grafana.user.login";
71      private static final String PROPERTY_GRAFANA_SERVER_USER_PWD = "grafana.user.pwd";
72      private static final String PROPERTY_GRAFANA_SERVER_SHOW_USER_ACCOUNT = "grafana.user.show";
73      private static final String GRAFANA_SERVER_URL = AppPropertiesService.getProperty( PROPERTY_GRAFANA_SERVER_URL );
74      private static final String GRAFANA_SERVER_LOGIN = AppPropertiesService.getProperty( PROPERTY_GRAFANA_SERVER_LOGIN );
75      private static final String GRAFANA_SERVER_PWD = AppPropertiesService.getProperty( PROPERTY_GRAFANA_SERVER_PWD );
76      private static final String GRAFANA_SERVER_USER_LOGIN = AppPropertiesService.getProperty( PROPERTY_GRAFANA_SERVER_USER_LOGIN );
77      private static final String GRAFANA_SERVER_USER_PWD = AppPropertiesService.getProperty( PROPERTY_GRAFANA_SERVER_USER_PWD );
78      private static final boolean GRAFANA_SERVER_SHOW_USER_ACCOUNT = AppPropertiesService.getPropertyBoolean( PROPERTY_GRAFANA_SERVER_SHOW_USER_ACCOUNT, false );
79      private static DashboardService _instance = null;
80      private static RequestAuthenticator _authenticator = new BasicAuthorizationAuthenticator( GRAFANA_SERVER_LOGIN, GRAFANA_SERVER_PWD );
81  
82      /** Private constructor */
83      private DashboardService( )
84      {
85      }
86  
87      public static DashboardService getInstance( )
88      {
89          if ( _instance == null )
90          {
91              _instance = new DashboardService( );
92          }
93          return _instance;
94      }
95  
96      /**
97       * Get the list of all dashboards
98       * 
99       * @return The list of dashboards
100      * @throws NoGrafanaDashboardException
101      *             if no Grafana index was found
102      * @throws NoGrafanaServerException
103      *             if no Grafana server was found
104      */
105     public List<Dashboard> getDashboards( ) throws NoGrafanaDashboardException, NoGrafanaServerException
106     {
107         List<Dashboard> listDashboards = new ArrayList<Dashboard>( );
108         HttpAccess httpAccess = new HttpAccess( );
109         Map<String, String> headers = new HashMap<>( );
110         try
111         {
112             String strJSON;
113 
114             if ( StringUtil.isAnyEmpty( GRAFANA_SERVER_LOGIN ) )
115             {
116                 strJSON = httpAccess.doGet( GRAFANA_SERVER_URL + GRAFANA_DASHBOARD_LIST_URL );
117             }
118 
119             strJSON = httpAccess.doGet( GRAFANA_SERVER_URL + GRAFANA_DASHBOARD_LIST_URL, _authenticator, null, headers );
120             List<Dashboard> listAvailableDashboards = getListDashboard( strJSON );
121             for ( Dashboard availbaleDashboard : listAvailableDashboards )
122             {
123                 Dashboard dashboard = DashboardHome.findByGrafanaId( availbaleDashboard.getIdGrafanaDashboard( ) );
124                 if ( dashboard != null )
125                 {
126                     listDashboards.add( dashboard );
127                 }
128                 else
129                 {
130                     listDashboards.add( availbaleDashboard );
131                 }
132             }
133         }
134         catch( HttpAccessException ex )
135         {
136             if ( ex.getMessage( ).indexOf( NOT_FOUND ) > 0 )
137             {
138                 throw new NoGrafanaDashboardException( ex.getMessage( ) );
139             }
140             else
141             {
142                 throw new NoGrafanaServerException( ex.getMessage( ) );
143             }
144         }
145         return listDashboards;
146     }
147 
148     /**
149      * Get the list of all dashboard
150      * 
151      * @param strJSON
152      *            The list of dashboard as JSON provided by Elastic
153      * @return The list
154      */
155     public List<Dashboard> getListDashboard( String strJSON )
156     {
157         List<Dashboard> listDashBoard = new ArrayList<Dashboard>( );
158 
159         JSONArray arr = new JSONArray( strJSON );
160         for ( int i = 0; i < arr.length( ); i++ )
161         {
162             JSONObject document = arr.getJSONObject( i );
163             if ( document.getString( "type" ).equals( "dash-db" ) )
164             {
165                 Dashboardana/business/Dashboard.html#Dashboard">Dashboard dashboard = new Dashboard( );
166                 dashboard.setIdGrafanaDashboard( document.getString( "uid" ) );
167                 dashboard.setTitle( document.getString( "title" ) );
168                 dashboard.setURI( document.getString( "uri" ) );
169                 listDashBoard.add( dashboard );
170             }
171         }
172         return listDashBoard;
173     }
174 
175     /**
176      * Get Grafana server URL
177      * 
178      * @return The URL
179      */
180     public String getGrafanaServerUrl( )
181     {
182         return GRAFANA_SERVER_URL;
183     }
184 
185     /**
186      * Get Grafana server user login
187      * 
188      * @return The URL
189      */
190     public String getGrafanaServerUserLogin( )
191     {
192         return GRAFANA_SERVER_USER_LOGIN;
193     }
194 
195     /**
196      * Get Grafana server user password
197      * 
198      * @return The URL
199      */
200     public String getGrafanaServerUserPassword( )
201     {
202         return GRAFANA_SERVER_USER_PWD;
203     }
204 
205     /**
206      * is Grafana server user should showed
207      * 
208      * @return The URL
209      */
210     public boolean isGrafanaServerUserShow( )
211     {
212         return GRAFANA_SERVER_SHOW_USER_ACCOUNT;
213     }
214 
215     /**
216      * Insert all dashboard to database
217      */
218     public void createAllDashboards( )
219     {
220         try
221         {
222             List<Dashboard> listDashboards = getDashboards( );
223             for ( Dashboard dashboard : listDashboards )
224             {
225                 DashboardHome.createOrUpdate( dashboard );
226             }
227         }
228         catch( NoGrafanaServerException e )
229         {
230             AppLogService.error( "Unable to connect to Grafana server", e );
231         }
232         catch( NoGrafanaDashboardException e )
233         {
234             AppLogService.error( "Unable to find Grafana index", e );
235         }
236     }
237 
238     /**
239      * Insert a dashboard to database
240      */
241     public void createDashboard( Dashboard dashboard )
242     {
243         DashboardHome.createOrUpdate( dashboard );
244     }
245 
246     /**
247      * Return a dashboard list filtered by RBAC authorizations.
248      * 
249      * @param listDashboard
250      * @param request
251      * @return a new dashboard list, according to RBAC authorizations.
252      */
253     public List<Dashboard> filterDashboardListRBAC( List<Dashboard> listDashboard, HttpServletRequest request )
254     {
255         List<Dashboard> listFilteredDashboards = new ArrayList<Dashboard>( );
256         AdminUser user = AdminUserService.getAdminUser( request );
257         for ( Dashboard dashboard : listDashboard )
258         {
259             Dashboard storedDashboard = DashboardHome.findByGrafanaId( dashboard.getIdGrafanaDashboard( ) );
260             if ( RBACService.isAuthorized( storedDashboard, GrafanaConstants.DASHBOARD_PERMISSION_VIEW, user ) )
261             {
262                 listFilteredDashboards.add( dashboard );
263             }
264         }
265         return listFilteredDashboards;
266     }
267 
268     /**
269      * Delete given dashboard and RBACs related to it
270      * 
271      * @param nIdDashboard
272      */
273     public void deleteDashboard( int nIdDashboard )
274     {
275         // First delete RBAC Resource related to given id dashboard
276         RBACHome.removeForResource( GrafanaConstants.DASHBOARD_RESOURCE_TYPE, Integer.toString( nIdDashboard ) );
277         // Then delete Dashboard
278         DashboardHome.delete( nIdDashboard );
279     }
280 }