8080
8181import org .joda .time .DateTime ;
8282
83+ import org .json .JSONException ;
8384import org .json .JSONObject ;
8485
8586import com .cloud .utils .exception .CloudRuntimeException ;
@@ -139,22 +140,25 @@ public BackrollClient(final String url, final String appname, final String passw
139140 }
140141 }
141142
142- public String startBackupJob (final String jobId )
143- throws ClientProtocolException , IOException , ParseException , NotOkBodyException {
143+ public String startBackupJob (final String jobId ) {
144144 logger .info ("Trying to start backup for Backroll job: {}" , jobId );
145145
146- ensureLoggedIn ();
147-
148- return this .<BackrollTaskRequestResponse >parse (okBody (
149- post (String .format ("/tasks/singlebackup/%s" , jobId ), null ))).location
150- .replace ("/api/v1/status/" , "" );
146+ try {
147+ loginIfAuthenticationFailed ();
148+ return this .<BackrollTaskRequestResponse >parse (okBody (
149+ post (String .format ("/tasks/singlebackup/%s" , jobId ), null ))).location
150+ .replace ("/api/v1/status/" , "" );
151+ } catch (final Exception e ) {
152+ logger .error ("Failed to start Backroll backup job due to: {}" , e .getMessage ());
153+ }
154+ return null ;
151155 }
152156
153157 public String getBackupOfferingUrl ()
154158 throws ClientProtocolException , IOException , ParseException , NotOkBodyException {
155159 logger .info ("Trying to list backroll backup policies" );
156160
157- ensureLoggedIn ();
161+ loginIfAuthenticationFailed ();
158162
159163 return this .<BackrollTaskRequestResponse >parse (okBody (get ("/backup_policies" ))).location .replace ("/api/v1" ,
160164 "" );
@@ -164,7 +168,7 @@ public List<BackupOffering> getBackupOfferings(String idTask)
164168 throws ParseException , NotOkBodyException , ClientProtocolException , IOException , InterruptedException {
165169 logger .info ("Trying to list backroll backup policies" );
166170
167- ensureLoggedIn ();
171+ loginIfAuthenticationFailed ();
168172
169173 BackupPoliciesResponse backupPoliciesResponse = waitGet (idTask );
170174
@@ -178,7 +182,7 @@ public List<BackupOffering> getBackupOfferings(String idTask)
178182 public void restoreVMFromBackup (final String vmId , final String backupName ) throws Exception {
179183 logger .info ("Start restore backup with backroll with backup {} for vm {}" , backupName , vmId );
180184
181- ensureLoggedIn ();
185+ loginIfAuthenticationFailed ();
182186
183187 JSONObject jsonBody = new JSONObject ();
184188 jsonBody .put ("virtual_machine_id" , vmId );
@@ -203,7 +207,7 @@ public BackrollTaskStatus checkBackupTaskStatus(String taskId)
203207 throws ParseException , IOException , NotOkBodyException {
204208 logger .info ("Trying to get backup status for Backroll task: {}" , taskId );
205209
206- ensureLoggedIn ();
210+ loginIfAuthenticationFailed ();
207211
208212 BackrollTaskStatus status = new BackrollTaskStatus ();
209213
@@ -221,27 +225,32 @@ public BackrollTaskStatus checkBackupTaskStatus(String taskId)
221225 return status ;
222226 }
223227
224- public void deleteBackup (final String vmId , final String backupName )
225- throws Exception {
228+ public boolean deleteBackup (final String vmId , final String backupName )
229+ throws ClientProtocolException , IOException {
226230 logger .info ("Trying to delete backup {} for vm {} using Backroll" , vmId , backupName );
227231
228- ensureLoggedIn ();
232+ loginIfAuthenticationFailed ();
229233
230- String urlToRequest = this .<BackrollTaskRequestResponse >parse (okBody (delete (
231- String .format ("/virtualmachines/%s/backups/%s" , vmId , backupName )))).location
232- .replace ("/api/v1" , "" );
234+ try {
235+ String urlToRequest = this .<BackrollTaskRequestResponse >parse (okBody (delete (
236+ String .format ("/virtualmachines/%s/backups/%s" , vmId , backupName )))).location
237+ .replace ("/api/v1" , "" );
233238
234- BackrollBackupsFromVMResponse backrollBackupsFromVMResponse = waitGet (urlToRequest );
235- logger .debug (backrollBackupsFromVMResponse .state );
236- if (!backrollBackupsFromVMResponse .state .equals (TaskState .SUCCESS )) {
237- throw new Exception ("Backroll task failed." );
239+ BackrollBackupsFromVMResponse backrollBackupsFromVMResponse = waitGet (urlToRequest );
240+ logger .debug (backrollBackupsFromVMResponse .state );
241+ return backrollBackupsFromVMResponse .state .equals (TaskState .SUCCESS );
242+ } catch (final NotOkBodyException e ) {
243+ return false ;
244+ } catch (final Exception e ) {
245+ logger .error ("Failed to delete backup using Backroll due to: {}" , e .getMessage ());
238246 }
247+ return false ;
239248 }
240249
241250 public Metric getVirtualMachineMetrics (final String vmId ) throws ClientProtocolException , IOException {
242251 logger .info ("Trying to retrieve virtual machine metric from Backroll for vm {}" , vmId );
243252
244- ensureLoggedIn ();
253+ loginIfAuthenticationFailed ();
245254
246255 Metric metric = new Metric (0L , 0L );
247256
@@ -276,7 +285,7 @@ public BackrollBackupMetrics getBackupMetrics(String vmId, String backupId) thro
276285 JsonProcessingException , ParseException , IOException , NotOkBodyException , InterruptedException {
277286 logger .info ("Trying to get backup metrics for VM: {}, and backup: {}" , vmId , backupId );
278287
279- ensureLoggedIn ();
288+ loginIfAuthenticationFailed ();
280289
281290 String urlToRequest = this .<BackrollTaskRequestResponse >parse (okBody (get (
282291 String .format ("/virtualmachines/%s/backups/%s" , vmId , backupId )))).location .replace ("/api/v1" , "" );
@@ -323,20 +332,26 @@ public List<BackrollVmBackup> getAllBackupsfromVirtualMachine(String vmId) {
323332 }
324333
325334 private HttpResponse post (final String path , final JSONObject json ) throws IOException {
335+ String xml = null ;
336+ StringEntity params = null ;
337+ if (json != null ) {
338+ logger .debug ("JSON {}" , json .toString ());
339+ params = new StringEntity (json .toString (), ContentType .APPLICATION_JSON );
340+ }
341+
326342 String url = apiURI .toString () + path ;
327343 final HttpPost request = new HttpPost (url );
328344
345+ if (params != null ) {
346+ request .setEntity (params );
347+ }
348+
329349 request .setHeader (HttpHeaders .AUTHORIZATION , "Bearer " + backrollToken );
330350 request .setHeader ("Content-type" , "application/json" );
331351
332- if (json != null ) {
333- logger .debug ("JSON {}" , json .toString ());
334- request .setEntity (new StringEntity (json .toString (), ContentType .APPLICATION_JSON ));
335- }
336-
337352 final HttpResponse response = httpClient .execute (request );
338353
339- logger .debug ("Response received in POST request with body {} is: {} for URL {}." , json , response .toString (),
354+ logger .debug ("Response received in POST request with body {} is: {} for URL {}." , xml , response .toString (),
340355 url );
341356
342357 return response ;
@@ -363,14 +378,9 @@ protected HttpResponse delete(final String path) throws IOException {
363378 return response ;
364379 }
365380
366- private boolean isResponseOk (final HttpResponse response ) {
367- switch (response .getStatusLine ().getStatusCode ()) {
368- case HttpStatus .SC_OK :
369- case HttpStatus .SC_ACCEPTED :
370- return true ;
371- default :
372- return false ;
373- }
381+ private boolean isResponseAuthorized (final HttpResponse response ) {
382+ return response .getStatusLine ().getStatusCode () == HttpStatus .SC_OK
383+ || response .getStatusLine ().getStatusCode () == HttpStatus .SC_ACCEPTED ;
374384 }
375385
376386 public class NotOkBodyException extends Exception {
@@ -388,15 +398,18 @@ public HttpResponse getResponse() {
388398
389399 private String okBody (final HttpResponse response )
390400 throws ParseException , IOException , NotOkBodyException {
391- if (isResponseOk (response )) {
392- HttpEntity bodyEntity = response .getEntity ();
393- try {
394- return EntityUtils .toString (bodyEntity );
395- } finally {
396- EntityUtils .consumeQuietly (bodyEntity );
397- }
401+ switch (response .getStatusLine ().getStatusCode ()) {
402+ case HttpStatus .SC_OK :
403+ case HttpStatus .SC_ACCEPTED :
404+ HttpEntity bodyEntity = response .getEntity ();
405+ try {
406+ return EntityUtils .toString (bodyEntity );
407+ } finally {
408+ EntityUtils .consumeQuietly (bodyEntity );
409+ }
410+ default :
411+ throw new NotOkBodyException (response );
398412 }
399- throw new NotOkBodyException (response );
400413 }
401414
402415 private <T > T parse (final String json )
@@ -428,15 +441,15 @@ private boolean isAuthenticated() {
428441 boolean result = false ;
429442 try {
430443 final HttpResponse response = post ("/auth" , null );
431- result = isResponseOk (response );
432- EntityUtils .consumeQuietly (response .getEntity ()); // TODO Move to a finally clause ?
444+ result = isResponseAuthorized (response );
445+ EntityUtils .consumeQuietly (response .getEntity ());
433446 } catch (IOException e ) {
434447 logger .error ("Failed to authenticate to Backroll due to: {}" , e .getMessage ());
435448 }
436449 return result ;
437450 }
438451
439- private void ensureLoggedIn () throws ClientProtocolException , IOException {
452+ private void loginIfAuthenticationFailed () throws ClientProtocolException , IOException {
440453 if (!isAuthenticated ()) {
441454 login (appname , password );
442455 }
0 commit comments