1/**
2 * API utilities service
3 *
4 * @module app/common/services/api-utils
5 * @exports APIUtils
6 * @name APIUtils
7 */
8
9window.angular && (function(angular) {
10  'use strict';
11  angular.module('app.common.services').factory('APIUtils', [
12    '$http', 'Constants', '$q', 'dataService', '$interval',
13    function($http, Constants, $q, DataService, $interval) {
14      var getScaledValue = function(value, scale) {
15        scale = scale + '';
16        scale = parseInt(scale, 10);
17        var power = Math.abs(parseInt(scale, 10));
18
19        if (scale > 0) {
20          value = value * Math.pow(10, power);
21        } else if (scale < 0) {
22          value = value / Math.pow(10, power);
23        }
24        return value;
25      };
26      var SERVICE = {
27        API_CREDENTIALS: Constants.API_CREDENTIALS,
28        API_RESPONSE: Constants.API_RESPONSE,
29        CHASSIS_POWER_STATE: Constants.CHASSIS_POWER_STATE,
30        HOST_STATE_TEXT: Constants.HOST_STATE,
31        HOST_STATE: Constants.HOST_STATE,
32        LED_STATE: Constants.LED_STATE,
33        LED_STATE_TEXT: Constants.LED_STATE_TEXT,
34        HOST_SESSION_STORAGE_KEY: Constants.API_CREDENTIALS.host_storage_key,
35        getChassisState: function() {
36          var deferred = $q.defer();
37          $http({
38            method: 'GET',
39            url: DataService.getHost() +
40                '/xyz/openbmc_project/state/chassis0/attr/CurrentPowerState',
41            withCredentials: true
42          })
43              .then(
44                  function(response) {
45                    var json = JSON.stringify(response.data);
46                    var content = JSON.parse(json);
47                    deferred.resolve(content.data);
48                  },
49                  function(error) {
50                    console.log(error);
51                    deferred.reject(error);
52                  });
53          return deferred.promise;
54        },
55        validIPV4IP: function(ip) {
56          // Checks for [0-255].[0-255].[0-255].[0-255]
57          return ip.match(
58              /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/);
59        },
60        getRedfishSysName: function() {
61          return $http({
62                   method: 'GET',
63                   url: DataService.getHost() + '/redfish/v1/Systems',
64                   withCredentials: true
65                 })
66              .then(
67                  function(response) {
68                    var sysUrl = response.data['Members'][0]['@odata.id'];
69                    return sysUrl.split('/').pop(-1);
70                  },
71                  function(error) {
72                    console.log(JSON.stringify(error));
73                  });
74        },
75        getSystemLogs: function(recordType) {
76          var uri = '/redfish/v1/Systems/' + DataService.systemName +
77              '/LogServices/EventLog/Entries';
78          return $http({
79                   method: 'GET',
80                   url: DataService.getHost() + uri,
81                   withCredentials: true
82                 })
83              .then(
84                  function(response) {
85                    var logEntries = [];
86                    angular.forEach(response.data['Members'], function(log) {
87                      if (log.hasOwnProperty('EntryType')) {
88                        if (log['EntryType'] == recordType) {
89                          logEntries.push(log);
90                        }
91                      }
92                    });
93                    return logEntries;
94                  },
95                  function(error) {
96                    console.log(JSON.stringify(error));
97                  });
98        },
99        clearSystemLogs: function() {
100          var uri = '/redfish/v1/Systems/' + DataService.systemName +
101              '/LogServices/EventLog/Actions/LogService.ClearLog';
102          return $http({
103            method: 'POST',
104            url: DataService.getHost() + uri,
105            withCredentials: true
106          });
107        },
108        deleteObject: function(path) {
109          return $http({
110                   method: 'POST',
111                   url: DataService.getHost() + path + '/action/Delete',
112                   withCredentials: true,
113                   data: JSON.stringify({'data': []})
114                 })
115              .then(function(response) {
116                return response.data;
117              });
118        },
119        getHostState: function() {
120          var deferred = $q.defer();
121          $http({
122            method: 'GET',
123            url: DataService.getHost() +
124                '/xyz/openbmc_project/state/host0/attr/CurrentHostState',
125            withCredentials: true
126          })
127              .then(
128                  function(response) {
129                    var json = JSON.stringify(response.data);
130                    var content = JSON.parse(json);
131                    deferred.resolve(content.data);
132                  },
133                  function(error) {
134                    console.log(error);
135                    deferred.reject(error);
136                  });
137          return deferred.promise;
138        },
139        getSNMPManagers: function() {
140          return $http({
141                   method: 'GET',
142                   url: DataService.getHost() +
143                       '/xyz/openbmc_project/network/snmp/manager/enumerate',
144                   withCredentials: true
145                 })
146              .then(function(response) {
147                return response.data;
148              });
149        },
150        pollHostStatusTillOn: function() {
151          var deferred = $q.defer();
152          var hostOnTimeout = setTimeout(function() {
153            ws.close();
154            deferred.reject(new Error(Constants.MESSAGES.POLL.HOST_ON_TIMEOUT));
155          }, Constants.TIMEOUT.HOST_ON);
156
157          var ws =
158              new WebSocket('wss://' + DataService.server_id + '/subscribe');
159          var data = JSON.stringify({
160            'paths': ['/xyz/openbmc_project/state/host0'],
161            'interfaces': ['xyz.openbmc_project.State.Host']
162          });
163          ws.onopen = function() {
164            ws.send(data);
165          };
166          ws.onmessage = function(evt) {
167            var content = JSON.parse(evt.data);
168            var hostState = content.properties.CurrentHostState;
169            if (hostState === Constants.HOST_STATE_TEXT.on_code) {
170              clearTimeout(hostOnTimeout);
171              ws.close();
172              deferred.resolve();
173            } else if (hostState === Constants.HOST_STATE_TEXT.error_code) {
174              clearTimeout(hostOnTimeout);
175              ws.close();
176              deferred.reject(new Error(Constants.MESSAGES.POLL.HOST_QUIESCED));
177            }
178          };
179        },
180
181        pollHostStatusTilReboot: function() {
182          var deferred = $q.defer();
183          var onState = Constants.HOST_STATE_TEXT.on_code;
184          var offState = Constants.HOST_STATE_TEXT.on_code;
185          var hostTimeout;
186          var setHostTimeout = function(message, timeout) {
187            hostTimeout = setTimeout(function() {
188              ws.close();
189              deferred.reject(new Error(message));
190            }, timeout);
191          };
192          var ws =
193              new WebSocket('wss://' + DataService.server_id + '/subscribe');
194          var data = JSON.stringify({
195            'paths': ['/xyz/openbmc_project/state/host0'],
196            'interfaces': ['xyz.openbmc_project.State.Host']
197          });
198          ws.onopen = function() {
199            ws.send(data);
200          };
201          setHostTimeout(
202              Constants.MESSAGES.POLL.HOST_OFF_TIMEOUT,
203              Constants.TIMEOUT.HOST_OFF);
204          var pollState = offState;
205          ws.onmessage = function(evt) {
206            var content = JSON.parse(evt.data);
207            var hostState = content.properties.CurrentHostState;
208            if (hostState === pollState) {
209              if (pollState === offState) {
210                clearTimeout(hostTimeout);
211                pollState = onState;
212                setHostTimeout(
213                    Constants.MESSAGES.POLL.HOST_ON_TIMEOUT,
214                    Constants.TIMEOUT.HOST_ON);
215              }
216              if (pollState === onState) {
217                clearTimeout(hostTimeout);
218                ws.close();
219                deferred.resolve();
220              }
221            } else if (hostState === Constants.HOST_STATE_TEXT.error_code) {
222              clearTimeout(hostTimeout);
223              ws.close();
224              deferred.reject(new Error(Constants.MESSAGES.POLL.HOST_QUIESCED));
225            }
226          };
227        },
228
229        pollHostStatusTillOff: function() {
230          var deferred = $q.defer();
231          var hostOffTimeout = setTimeout(function() {
232            ws.close();
233            deferred.reject(
234                new Error(Constants.MESSAGES.POLL.HOST_OFF_TIMEOUT));
235          }, Constants.TIMEOUT.HOST_OFF);
236
237          var ws =
238              new WebSocket('wss://' + DataService.server_id + '/subscribe');
239          var data = JSON.stringify({
240            'paths': ['/xyz/openbmc_project/state/host0'],
241            'interfaces': ['xyz.openbmc_project.State.Host']
242          });
243          ws.onopen = function() {
244            ws.send(data);
245          };
246          ws.onmessage = function(evt) {
247            var content = JSON.parse(evt.data);
248            var hostState = content.properties.CurrentHostState;
249            if (hostState === Constants.HOST_STATE_TEXT.off_code) {
250              clearTimeout(hostOffTimeout);
251              ws.close();
252              deferred.resolve();
253            }
254          };
255        },
256        addSNMPManager: function(address, port) {
257          return $http({
258                   method: 'POST',
259                   url: DataService.getHost() +
260                       '/xyz/openbmc_project/network/snmp/manager/action/Client',
261                   withCredentials: true,
262                   data: JSON.stringify({'data': [address, +port]})
263                 })
264              .then(function(response) {
265                return response.data;
266              });
267        },
268        setSNMPManagerPort: function(snmpManagerPath, port) {
269          return $http({
270                   method: 'PUT',
271                   url: DataService.getHost() + snmpManagerPath + '/attr/Port',
272                   withCredentials: true,
273                   data: JSON.stringify({'data': +port})
274                 })
275              .then(function(response) {
276                return response.data;
277              });
278        },
279        setSNMPManagerAddress: function(snmpManagerPath, address) {
280          return $http({
281                   method: 'PUT',
282                   url: DataService.getHost() + snmpManagerPath +
283                       '/attr/Address',
284                   withCredentials: true,
285                   data: JSON.stringify({'data': address})
286                 })
287              .then(function(response) {
288                return response.data;
289              });
290        },
291        getNetworkInfo: function() {
292          var deferred = $q.defer();
293          $http({
294            method: 'GET',
295            url: DataService.getHost() +
296                '/xyz/openbmc_project/network/enumerate',
297            withCredentials: true
298          })
299              .then(
300                  function(response) {
301                    var json = JSON.stringify(response.data);
302                    var content = JSON.parse(json);
303                    var hostname = '';
304                    var defaultgateway = '';
305                    var macAddress = '';
306
307                    function parseNetworkData(content) {
308                      var data = {
309                        interface_ids: [],
310                        interfaces: {},
311                        ip_addresses: {ipv4: [], ipv6: []},
312                      };
313                      var interfaceId = '', keyParts = [], interfaceHash = '',
314                          interfaceType = '';
315                      for (var key in content.data) {
316                        if (key.match(/network\/eth\d+(_\d+)?$/ig)) {
317                          interfaceId = key.split('/').pop();
318                          if (data.interface_ids.indexOf(interfaceId) == -1) {
319                            data.interface_ids.push(interfaceId);
320                            data.interfaces[interfaceId] = {
321                              interfaceIname: '',
322                              DomainName: '',
323                              MACAddress: '',
324                              Nameservers: [],
325                              DHCPEnabled: 0,
326                              ipv4: {ids: [], values: []},
327                              ipv6: {ids: [], values: []}
328                            };
329                            data.interfaces[interfaceId].MACAddress =
330                                content.data[key].MACAddress;
331                            data.interfaces[interfaceId].DomainName =
332                                content.data[key].DomainName.join(' ');
333                            data.interfaces[interfaceId].Nameservers =
334                                content.data[key].Nameservers;
335                            data.interfaces[interfaceId].DHCPEnabled =
336                                content.data[key].DHCPEnabled;
337                          }
338                        } else if (
339                            key.match(
340                                /network\/eth\d+(_\d+)?\/ipv[4|6]\/[a-z0-9]+$/ig)) {
341                          keyParts = key.split('/');
342                          interfaceHash = keyParts.pop();
343                          interfaceType = keyParts.pop();
344                          interfaceId = keyParts.pop();
345
346                          if (data.interfaces[interfaceId][interfaceType]
347                                  .ids.indexOf(interfaceHash) == -1) {
348                            data.interfaces[interfaceId][interfaceType]
349                                .ids.push(interfaceHash);
350                            data.interfaces[interfaceId][interfaceType]
351                                .values.push(content.data[key]);
352                            data.ip_addresses[interfaceType].push(
353                                content.data[key]['Address']);
354                          }
355                        }
356                      }
357                      return data;
358                    }
359
360                    if (content.data.hasOwnProperty(
361                            '/xyz/openbmc_project/network/config')) {
362                      if (content.data['/xyz/openbmc_project/network/config']
363                              .hasOwnProperty('HostName')) {
364                        hostname =
365                            content.data['/xyz/openbmc_project/network/config']
366                                .HostName;
367                      }
368                      if (content.data['/xyz/openbmc_project/network/config']
369                              .hasOwnProperty('DefaultGateway')) {
370                        defaultgateway =
371                            content.data['/xyz/openbmc_project/network/config']
372                                .DefaultGateway;
373                      }
374                    }
375
376                    if (content.data.hasOwnProperty(
377                            '/xyz/openbmc_project/network/eth0') &&
378                        content.data['/xyz/openbmc_project/network/eth0']
379                            .hasOwnProperty('MACAddress')) {
380                      macAddress =
381                          content.data['/xyz/openbmc_project/network/eth0']
382                              .MACAddress;
383                    }
384
385                    deferred.resolve({
386                      data: content.data,
387                      hostname: hostname,
388                      defaultgateway: defaultgateway,
389                      mac_address: macAddress,
390                      formatted_data: parseNetworkData(content)
391                    });
392                  },
393                  function(error) {
394                    console.log(error);
395                    deferred.reject(error);
396                  });
397          return deferred.promise;
398        },
399        setMACAddress: function(interface_name, mac_address) {
400          return $http({
401                   method: 'PUT',
402                   url: DataService.getHost() +
403                       '/xyz/openbmc_project/network/' + interface_name +
404                       '/attr/MACAddress',
405                   withCredentials: true,
406                   data: JSON.stringify({'data': mac_address})
407                 })
408              .then(function(response) {
409                return response.data;
410              });
411        },
412        setDefaultGateway: function(defaultGateway) {
413          return $http({
414                   method: 'PUT',
415                   url: DataService.getHost() +
416                       '/xyz/openbmc_project/network/config/attr/DefaultGateway',
417                   withCredentials: true,
418                   data: JSON.stringify({'data': defaultGateway})
419                 })
420              .then(function(response) {
421                return response.data;
422              });
423        },
424        setDHCPEnabled: function(interfaceName, dhcpEnabled) {
425          return $http({
426                   method: 'PUT',
427                   url: DataService.getHost() +
428                       '/xyz/openbmc_project/network/' + interfaceName +
429                       '/attr/DHCPEnabled',
430                   withCredentials: true,
431                   data: JSON.stringify({'data': dhcpEnabled})
432                 })
433              .then(function(response) {
434                return response.data;
435              });
436        },
437        setNameservers: function(interfaceName, dnsServers) {
438          return $http({
439                   method: 'PUT',
440                   url: DataService.getHost() +
441                       '/xyz/openbmc_project/network/' + interfaceName +
442                       '/attr/Nameservers',
443                   withCredentials: true,
444                   data: JSON.stringify({'data': dnsServers})
445                 })
446              .then(function(response) {
447                return response.data;
448              });
449        },
450        deleteIPV4: function(interfaceName, networkID) {
451          return $http({
452                   method: 'POST',
453                   url: DataService.getHost() +
454                       '/xyz/openbmc_project/network/' + interfaceName +
455                       '/ipv4/' + networkID + '/action/Delete',
456                   withCredentials: true,
457                   data: JSON.stringify({'data': []})
458                 })
459              .then(function(response) {
460                return response.data;
461              });
462        },
463        addIPV4: function(
464            interfaceName, ipAddress, netmaskPrefixLength, gateway) {
465          return $http({
466                   method: 'POST',
467                   url: DataService.getHost() +
468                       '/xyz/openbmc_project/network/' + interfaceName +
469                       '/action/IP',
470                   withCredentials: true,
471                   data: JSON.stringify({
472                     'data': [
473                       'xyz.openbmc_project.Network.IP.Protocol.IPv4',
474                       ipAddress, +netmaskPrefixLength, gateway
475                     ]
476                   })
477                 })
478              .then(function(response) {
479                return response.data;
480              });
481        },
482        getLEDState: function() {
483          var deferred = $q.defer();
484          $http({
485            method: 'GET',
486            url: DataService.getHost() +
487                '/xyz/openbmc_project/led/groups/enclosure_identify',
488            withCredentials: true
489          })
490              .then(
491                  function(response) {
492                    var json = JSON.stringify(response.data);
493                    var content = JSON.parse(json);
494                    deferred.resolve(content.data.Asserted);
495                  },
496                  function(error) {
497                    console.log(error);
498                    deferred.reject(error);
499                  });
500          return deferred.promise;
501        },
502        login: function(username, password, callback) {
503          $http({
504            method: 'POST',
505            url: DataService.getHost() + '/login',
506            withCredentials: true,
507            data: JSON.stringify({'data': [username, password]})
508          })
509              .then(
510                  function(response) {
511                    if (callback) {
512                      callback(response.data);
513                    }
514                  },
515                  function(error) {
516                    if (callback) {
517                      if (error && error.status && error.status == 'error') {
518                        callback(error);
519                      } else {
520                        callback(error, true);
521                      }
522                    }
523                    console.log(error);
524                  });
525        },
526        logout: function(callback) {
527          $http({
528            method: 'POST',
529            url: DataService.getHost() + '/logout',
530            withCredentials: true,
531            data: JSON.stringify({'data': []})
532          })
533              .then(
534                  function(response) {
535                    if (callback) {
536                      callback(response.data);
537                    }
538                  },
539                  function(error) {
540                    if (callback) {
541                      callback(null, error);
542                    }
543                    console.log(error);
544                  });
545        },
546        getAccountServiceRoles: function() {
547          var roles = [];
548
549          return $http({
550                   method: 'GET',
551                   url: DataService.getHost() +
552                       '/redfish/v1/AccountService/Roles',
553                   withCredentials: true
554                 })
555              .then(
556                  function(response) {
557                    var members = response.data['Members'];
558                    angular.forEach(members, function(member) {
559                      roles.push(member['@odata.id'].split('/').pop());
560                    });
561                    return roles;
562                  },
563                  function(error) {
564                    console.log(error);
565                  });
566        },
567        getAllUserAccounts: function() {
568          var deferred = $q.defer();
569          var promises = [];
570          var users = [];
571
572          $http({
573            method: 'GET',
574            url: DataService.getHost() + '/redfish/v1/AccountService/Accounts',
575            withCredentials: true
576          })
577              .then(
578                  function(response) {
579                    var members = response.data['Members'];
580                    angular.forEach(members, function(member) {
581                      promises.push(
582                          $http({
583                            method: 'GET',
584                            url: DataService.getHost() + member['@odata.id'],
585                            withCredentials: true
586                          }).then(function(res) {
587                            return res.data;
588                          }));
589                    });
590
591                    $q.all(promises).then(
592                        function(results) {
593                          deferred.resolve(results);
594                        },
595                        function(errors) {
596                          deferred.reject(errors);
597                        });
598                  },
599                  function(error) {
600                    console.log(error);
601                    deferred.reject(error);
602                  });
603          return deferred.promise;
604        },
605
606        getAllUserAccountProperties: function(callback) {
607          return $http({
608                   method: 'GET',
609                   url: DataService.getHost() + '/redfish/v1/AccountService',
610                   withCredentials: true
611                 })
612              .then(
613                  function(response) {
614                    return response.data;
615                  },
616                  function(error) {
617                    console.log(error);
618                  });
619        },
620
621        saveUserAccountProperties: function(lockoutduration, lockoutthreshold) {
622          var data = {};
623          if (lockoutduration != undefined) {
624            data['AccountLockoutDuration'] = lockoutduration;
625          }
626          if (lockoutthreshold != undefined) {
627            data['AccountLockoutThreshold'] = lockoutthreshold;
628          }
629
630          return $http({
631            method: 'PATCH',
632            url: DataService.getHost() + '/redfish/v1/AccountService',
633            withCredentials: true,
634            data: data
635          });
636        },
637
638        createUser: function(user, passwd, role, enabled) {
639          var data = {};
640          data['UserName'] = user;
641          data['Password'] = passwd;
642          data['RoleId'] = role;
643          data['Enabled'] = enabled;
644
645          return $http({
646            method: 'POST',
647            url: DataService.getHost() + '/redfish/v1/AccountService/Accounts',
648            withCredentials: true,
649            data: data
650          });
651        },
652        updateUser: function(user, newUser, passwd, role, enabled) {
653          var data = {};
654          if ((newUser !== undefined) && (newUser != null)) {
655            data['UserName'] = newUser;
656          }
657          if ((role !== undefined) && (role != null)) {
658            data['RoleId'] = role;
659          }
660          if ((enabled !== undefined) && (enabled != null)) {
661            data['Enabled'] = enabled;
662          }
663          if ((passwd !== undefined) && (passwd != null)) {
664            data['Password'] = passwd;
665          }
666          return $http({
667            method: 'PATCH',
668            url: DataService.getHost() +
669                '/redfish/v1/AccountService/Accounts/' + user,
670            withCredentials: true,
671            data: data
672          });
673        },
674        deleteUser: function(user) {
675          return $http({
676            method: 'DELETE',
677            url: DataService.getHost() +
678                '/redfish/v1/AccountService/Accounts/' + user,
679            withCredentials: true,
680          });
681        },
682        chassisPowerOff: function() {
683          var deferred = $q.defer();
684          $http({
685            method: 'PUT',
686            url: DataService.getHost() +
687                '/xyz/openbmc_project/state/chassis0/attr/RequestedPowerTransition',
688            withCredentials: true,
689            data: JSON.stringify(
690                {'data': 'xyz.openbmc_project.State.Chassis.Transition.Off'})
691          })
692              .then(
693                  function(response) {
694                    var json = JSON.stringify(response.data);
695                    var content = JSON.parse(json);
696                    deferred.resolve(content.status);
697                  },
698                  function(error) {
699                    console.log(error);
700                    deferred.reject(error);
701                  });
702          return deferred.promise;
703        },
704        setLEDState: function(state) {
705          return $http({
706            method: 'PUT',
707            url: DataService.getHost() +
708                '/xyz/openbmc_project/led/groups/enclosure_identify/attr/Asserted',
709            withCredentials: true,
710            data: JSON.stringify({'data': state})
711          })
712        },
713        bmcReboot: function() {
714          return $http({
715            method: 'PUT',
716            url: DataService.getHost() +
717                '/xyz/openbmc_project/state/bmc0/attr/RequestedBMCTransition',
718            withCredentials: true,
719            data: JSON.stringify(
720                {'data': 'xyz.openbmc_project.State.BMC.Transition.Reboot'})
721          });
722        },
723        getLastRebootTime: function() {
724          return $http({
725                   method: 'GET',
726                   url: DataService.getHost() +
727                       '/xyz/openbmc_project/state/bmc0/attr/LastRebootTime',
728                   withCredentials: true
729                 })
730              .then(function(response) {
731                return response.data;
732              });
733        },
734        hostPowerOn: function() {
735          var deferred = $q.defer();
736          $http({
737            method: 'PUT',
738            url: DataService.getHost() +
739                '/xyz/openbmc_project/state/host0/attr/RequestedHostTransition',
740            withCredentials: true,
741            data: JSON.stringify(
742                {'data': 'xyz.openbmc_project.State.Host.Transition.On'})
743          })
744              .then(
745                  function(response) {
746                    var json = JSON.stringify(response.data);
747                    var content = JSON.parse(json);
748                    deferred.resolve(content.status);
749                  },
750                  function(error) {
751                    console.log(error);
752                    deferred.reject(error);
753                  });
754          return deferred.promise;
755        },
756        hostPowerOff: function() {
757          var deferred = $q.defer();
758          $http({
759            method: 'PUT',
760            url: DataService.getHost() +
761                '/xyz/openbmc_project/state/host0/attr/RequestedHostTransition',
762            withCredentials: true,
763            data: JSON.stringify(
764                {'data': 'xyz.openbmc_project.State.Host.Transition.Off'})
765          })
766              .then(
767                  function(response) {
768                    var json = JSON.stringify(response.data);
769                    var content = JSON.parse(json);
770                    deferred.resolve(content.status);
771                  },
772                  function(error) {
773                    console.log(error);
774                    deferred.reject(error);
775                  });
776          return deferred.promise;
777        },
778        hostReboot: function() {
779          var deferred = $q.defer();
780          $http({
781            method: 'PUT',
782            url: DataService.getHost() +
783                '/xyz/openbmc_project/state/host0/attr/RequestedHostTransition',
784            withCredentials: true,
785            data: JSON.stringify(
786                {'data': 'xyz.openbmc_project.State.Host.Transition.Reboot'})
787          })
788              .then(
789                  function(response) {
790                    var json = JSON.stringify(response.data);
791                    var content = JSON.parse(json);
792                    deferred.resolve(content.status);
793                  },
794                  function(error) {
795                    console.log(error);
796                    deferred.reject(error);
797                  });
798
799          return deferred.promise;
800        },
801        hostShutdown: function(callback) {
802          $http({
803            method: 'POST',
804            url: DataService.getHost() + '/xyz/openbmc_project/state/host0',
805            withCredentials: true,
806            data: JSON.stringify({'data': []})
807          })
808              .then(
809                  function(response) {
810                    var json = JSON.stringify(response.data);
811                    var content = JSON.parse(json);
812                    if (callback) {
813                      return callback(content);
814                    }
815                  },
816                  function(error) {
817                    if (callback) {
818                      callback(error);
819                    } else {
820                      console.log(error);
821                    }
822                  });
823        },
824        getLastPowerTime: function() {
825          return $http({
826                   method: 'GET',
827                   url: DataService.getHost() +
828                       '/xyz/openbmc_project/state/chassis0/attr/LastStateChangeTime',
829                   withCredentials: true
830                 })
831              .then(function(response) {
832                return response.data;
833              });
834        },
835        getLogs: function() {
836          var deferred = $q.defer();
837          $http({
838            method: 'GET',
839            url: DataService.getHost() +
840                '/xyz/openbmc_project/logging/enumerate',
841            withCredentials: true
842          })
843              .then(
844                  function(response) {
845                    var json = JSON.stringify(response.data);
846                    var content = JSON.parse(json);
847                    var dataClone = JSON.parse(JSON.stringify(content.data));
848                    var data = [];
849                    var severityCode = '';
850                    var priority = '';
851                    var health = '';
852                    var relatedItems = [];
853                    var eventID = 'None';
854                    var description = 'None';
855
856                    for (var key in content.data) {
857                      if (content.data.hasOwnProperty(key) &&
858                          content.data[key].hasOwnProperty('Id')) {
859                        var severityFlags = {
860                          low: false,
861                          medium: false,
862                          high: false
863                        };
864                        severityCode =
865                            content.data[key].Severity.split('.').pop();
866                        priority =
867                            Constants.SEVERITY_TO_PRIORITY_MAP[severityCode];
868                        severityFlags[priority.toLowerCase()] = true;
869                        relatedItems = [];
870                        content.data[key].associations.forEach(function(item) {
871                          relatedItems.push(item[2]);
872                        });
873
874                        if (content.data[key].hasOwnProperty(['EventID'])) {
875                          eventID = content.data[key].EventID;
876                        }
877
878                        if (content.data[key].hasOwnProperty(['Description'])) {
879                          description = content.data[key].Description;
880                        }
881
882                        data.push(Object.assign(
883                            {
884                              path: key,
885                              copied: false,
886                              priority: priority,
887                              severity_code: severityCode,
888                              severity_flags: severityFlags,
889                              additional_data:
890                                  content.data[key].AdditionalData.join('\n'),
891                              type: content.data[key].Message,
892                              selected: false,
893                              search_text:
894                                  ('#' + content.data[key].Id + ' ' +
895                                   severityCode + ' ' +
896                                   content.data[key].Message + ' ' +
897                                   content.data[key].Severity + ' ' +
898                                   content.data[key].AdditionalData.join(' '))
899                                      .toLowerCase(),
900                              meta: false,
901                              confirm: false,
902                              related_items: relatedItems,
903                              eventID: eventID,
904                              description: description,
905                              data: {key: key, value: content.data[key]}
906                            },
907                            content.data[key]));
908                      }
909                    }
910                    deferred.resolve({data: data, original: dataClone});
911                  },
912                  function(error) {
913                    console.log(error);
914                    deferred.reject(error);
915                  });
916
917          return deferred.promise;
918        },
919        getAllSensorStatus: function(callback) {
920          $http({
921            method: 'GET',
922            url: DataService.getHost() +
923                '/xyz/openbmc_project/sensors/enumerate',
924            withCredentials: true
925          })
926              .then(
927                  function(response) {
928                    var json = JSON.stringify(response.data);
929                    var content = JSON.parse(json);
930                    var dataClone = JSON.parse(JSON.stringify(content.data));
931                    var sensorData = [];
932                    var severity = {};
933                    var title = '';
934                    var tempKeyParts = [];
935                    var order = 0;
936                    var customOrder = 0;
937
938                    function getSensorStatus(reading) {
939                      var severityFlags = {
940                        critical: false,
941                        warning: false,
942                        normal: false
943                      },
944                          severityText = '', order = 0;
945
946                      if (reading.hasOwnProperty('CriticalLow') &&
947                          reading.Value < reading.CriticalLow) {
948                        severityFlags.critical = true;
949                        severityText = 'critical';
950                        order = 2;
951                      } else if (
952                          reading.hasOwnProperty('CriticalHigh') &&
953                          reading.Value > reading.CriticalHigh) {
954                        severityFlags.critical = true;
955                        severityText = 'critical';
956                        order = 2;
957                      } else if (
958                          reading.hasOwnProperty('CriticalLow') &&
959                          reading.hasOwnProperty('WarningLow') &&
960                          reading.Value >= reading.CriticalLow &&
961                          reading.Value <= reading.WarningLow) {
962                        severityFlags.warning = true;
963                        severityText = 'warning';
964                        order = 1;
965                      } else if (
966                          reading.hasOwnProperty('WarningHigh') &&
967                          reading.hasOwnProperty('CriticalHigh') &&
968                          reading.Value >= reading.WarningHigh &&
969                          reading.Value <= reading.CriticalHigh) {
970                        severityFlags.warning = true;
971                        severityText = 'warning';
972                        order = 1;
973                      } else {
974                        severityFlags.normal = true;
975                        severityText = 'normal';
976                      }
977                      return {
978                        flags: severityFlags,
979                        severityText: severityText,
980                        order: order
981                      };
982                    }
983
984                    for (var key in content.data) {
985                      if (content.data.hasOwnProperty(key) &&
986                          content.data[key].hasOwnProperty('Unit')) {
987                        severity = getSensorStatus(content.data[key]);
988
989                        if (!content.data[key].hasOwnProperty('CriticalLow')) {
990                          content.data[key].CriticalLow = '--';
991                          content.data[key].CriticalHigh = '--';
992                        }
993
994                        if (!content.data[key].hasOwnProperty('WarningLow')) {
995                          content.data[key].WarningLow = '--';
996                          content.data[key].WarningHigh = '--';
997                        }
998
999                        tempKeyParts = key.split('/');
1000                        title = tempKeyParts.pop();
1001                        title = tempKeyParts.pop() + '_' + title;
1002                        title = title.split('_')
1003                                    .map(function(item) {
1004                                      return item.toLowerCase()
1005                                                 .charAt(0)
1006                                                 .toUpperCase() +
1007                                          item.slice(1);
1008                                    })
1009                                    .reduce(function(prev, el) {
1010                                      return prev + ' ' + el;
1011                                    });
1012
1013                        content.data[key].Value = getScaledValue(
1014                            content.data[key].Value, content.data[key].Scale);
1015                        content.data[key].CriticalLow = getScaledValue(
1016                            content.data[key].CriticalLow,
1017                            content.data[key].Scale);
1018                        content.data[key].CriticalHigh = getScaledValue(
1019                            content.data[key].CriticalHigh,
1020                            content.data[key].Scale);
1021                        content.data[key].WarningLow = getScaledValue(
1022                            content.data[key].WarningLow,
1023                            content.data[key].Scale);
1024                        content.data[key].WarningHigh = getScaledValue(
1025                            content.data[key].WarningHigh,
1026                            content.data[key].Scale);
1027                        if (Constants.SENSOR_SORT_ORDER.indexOf(
1028                                content.data[key].Unit) > -1) {
1029                          customOrder = Constants.SENSOR_SORT_ORDER.indexOf(
1030                              content.data[key].Unit);
1031                        } else {
1032                          customOrder = Constants.SENSOR_SORT_ORDER_DEFAULT;
1033                        }
1034
1035                        sensorData.push(Object.assign(
1036                            {
1037                              path: key,
1038                              selected: false,
1039                              confirm: false,
1040                              copied: false,
1041                              title: title,
1042                              unit:
1043                                  Constants
1044                                      .SENSOR_UNIT_MAP[content.data[key].Unit],
1045                              severity_flags: severity.flags,
1046                              status: severity.severityText,
1047                              order: severity.order,
1048                              custom_order: customOrder,
1049                              search_text:
1050                                  (title + ' ' + content.data[key].Value + ' ' +
1051                                   Constants.SENSOR_UNIT_MAP[content.data[key]
1052                                                                 .Unit] +
1053                                   ' ' + severity.severityText + ' ' +
1054                                   content.data[key].CriticalLow + ' ' +
1055                                   content.data[key].CriticalHigh + ' ' +
1056                                   content.data[key].WarningLow + ' ' +
1057                                   content.data[key].WarningHigh + ' ')
1058                                      .toLowerCase(),
1059                              original_data:
1060                                  {key: key, value: content.data[key]}
1061                            },
1062                            content.data[key]));
1063                      }
1064                    }
1065
1066                    callback(sensorData, dataClone);
1067                  },
1068                  function(error) {
1069                    console.log(error);
1070                  });
1071        },
1072        getActivation: function(imageId) {
1073          return $http({
1074                   method: 'GET',
1075                   url: DataService.getHost() +
1076                       '/xyz/openbmc_project/software/' + imageId +
1077                       '/attr/Activation',
1078                   withCredentials: true
1079                 })
1080              .then(function(response) {
1081                return response.data;
1082              });
1083        },
1084        getFirmwares: function() {
1085          var deferred = $q.defer();
1086          $http({
1087            method: 'GET',
1088            url: DataService.getHost() +
1089                '/xyz/openbmc_project/software/enumerate',
1090            withCredentials: true
1091          })
1092              .then(
1093                  function(response) {
1094                    var json = JSON.stringify(response.data);
1095                    var content = JSON.parse(json);
1096                    var data = [];
1097                    var isExtended = false;
1098                    var bmcActiveVersion = '';
1099                    var hostActiveVersion = '';
1100                    var imageType = '';
1101                    var extendedVersions = [];
1102                    var functionalImages = [];
1103
1104                    function getFormatedExtendedVersions(extendedVersion) {
1105                      var versions = [];
1106                      extendedVersion = extendedVersion.split(',');
1107
1108                      extendedVersion.forEach(function(item) {
1109                        var parts = item.split('-');
1110                        var numberIndex = 0;
1111                        for (var i = 0; i < parts.length; i++) {
1112                          if (/[0-9]/.test(parts[i])) {
1113                            numberIndex = i;
1114                            break;
1115                          }
1116                        }
1117                        var titlePart = parts.splice(0, numberIndex);
1118                        titlePart = titlePart.join('');
1119                        titlePart = titlePart[0].toUpperCase() +
1120                            titlePart.substr(1, titlePart.length);
1121                        var versionPart = parts.join('-');
1122                        versions.push({title: titlePart, version: versionPart});
1123                      });
1124
1125                      return versions;
1126                    }
1127
1128                    // Get the list of functional images so we can compare
1129                    // later if an image is functional
1130                    if (content.data[Constants.FIRMWARE.FUNCTIONAL_OBJPATH]) {
1131                      functionalImages =
1132                          content.data[Constants.FIRMWARE.FUNCTIONAL_OBJPATH]
1133                              .endpoints;
1134                    }
1135                    for (var key in content.data) {
1136                      if (content.data.hasOwnProperty(key) &&
1137                          content.data[key].hasOwnProperty('Version')) {
1138                        var activationStatus = '';
1139
1140                        // If the image is "Functional" use that for the
1141                        // activation status, else use the value of
1142                        // "Activation"
1143                        // github.com/openbmc/phosphor-dbus-interfaces/blob/master/xyz/openbmc_project/Software/Activation.interface.yaml
1144                        if (content.data[key].Activation) {
1145                          activationStatus =
1146                              content.data[key].Activation.split('.').pop();
1147                        }
1148
1149                        if (functionalImages.includes(key)) {
1150                          activationStatus = 'Functional';
1151                        }
1152
1153                        imageType = content.data[key].Purpose.split('.').pop();
1154                        isExtended = content.data[key].hasOwnProperty(
1155                                         'ExtendedVersion') &&
1156                            content.data[key].ExtendedVersion != '';
1157                        if (isExtended) {
1158                          extendedVersions = getFormatedExtendedVersions(
1159                              content.data[key].ExtendedVersion);
1160                        }
1161                        data.push(Object.assign(
1162                            {
1163                              path: key,
1164                              activationStatus: activationStatus,
1165                              imageId: key.split('/').pop(),
1166                              imageType: imageType,
1167                              isExtended: isExtended,
1168                              extended:
1169                                  {show: false, versions: extendedVersions},
1170                              data: {key: key, value: content.data[key]}
1171                            },
1172                            content.data[key]));
1173
1174                        if (activationStatus == 'Functional' &&
1175                            imageType == 'BMC') {
1176                          bmcActiveVersion = content.data[key].Version;
1177                        }
1178
1179                        if (activationStatus == 'Functional' &&
1180                            imageType == 'Host') {
1181                          hostActiveVersion = content.data[key].Version;
1182                        }
1183                      }
1184                    }
1185
1186                    deferred.resolve({
1187                      data: data,
1188                      bmcActiveVersion: bmcActiveVersion,
1189                      hostActiveVersion: hostActiveVersion
1190                    });
1191                  },
1192                  function(error) {
1193                    console.log(error);
1194                    deferred.reject(error);
1195                  });
1196
1197          return deferred.promise;
1198        },
1199        changePriority: function(imageId, priority) {
1200          return $http({
1201                   method: 'PUT',
1202                   url: DataService.getHost() +
1203                       '/xyz/openbmc_project/software/' + imageId +
1204                       '/attr/Priority',
1205                   withCredentials: true,
1206                   data: JSON.stringify({'data': priority})
1207                 })
1208              .then(function(response) {
1209                return response.data;
1210              });
1211        },
1212        deleteImage: function(imageId) {
1213          return $http({
1214                   method: 'POST',
1215                   url: DataService.getHost() +
1216                       '/xyz/openbmc_project/software/' + imageId +
1217                       '/action/Delete',
1218                   withCredentials: true,
1219                   data: JSON.stringify({'data': []})
1220                 })
1221              .then(function(response) {
1222                return response.data;
1223              });
1224        },
1225        activateImage: function(imageId) {
1226          return $http({
1227                   method: 'PUT',
1228                   url: DataService.getHost() +
1229                       '/xyz/openbmc_project/software/' + imageId +
1230                       '/attr/RequestedActivation',
1231                   withCredentials: true,
1232                   data: JSON.stringify(
1233                       {'data': Constants.FIRMWARE.ACTIVATE_FIRMWARE})
1234                 })
1235              .then(function(response) {
1236                return response.data;
1237              });
1238        },
1239        uploadImage: function(file) {
1240          return $http({
1241                   method: 'POST',
1242                   timeout: 5 * 60 * 1000,
1243                   url: DataService.getHost() + '/upload/image',
1244                   // Overwrite the default 'application/json' Content-Type
1245                   headers: {'Content-Type': 'application/octet-stream'},
1246                   withCredentials: true,
1247                   data: file
1248                 })
1249              .then(function(response) {
1250                return response.data;
1251              });
1252        },
1253        downloadImage: function(host, filename) {
1254          return $http({
1255                   method: 'POST',
1256                   url: DataService.getHost() +
1257                       '/xyz/openbmc_project/software/action/DownloadViaTFTP',
1258                   withCredentials: true,
1259                   data: JSON.stringify({'data': [filename, host]}),
1260                   responseType: 'arraybuffer'
1261                 })
1262              .then(function(response) {
1263                return response.data;
1264              });
1265        },
1266        getServerInfo: function() {
1267          // TODO: openbmc/openbmc#3117 Need a way via REST to get
1268          // interfaces so we can get the system object(s) by the looking
1269          // for the system interface.
1270          return $http({
1271                   method: 'GET',
1272                   url: DataService.getHost() +
1273                       '/xyz/openbmc_project/inventory/system',
1274                   withCredentials: true
1275                 })
1276              .then(function(response) {
1277                return response.data;
1278              });
1279        },
1280        getBMCTime: function() {
1281          return $http({
1282                   method: 'GET',
1283                   url: DataService.getHost() + '/xyz/openbmc_project/time/bmc',
1284                   withCredentials: true
1285                 })
1286              .then(function(response) {
1287                return response.data;
1288              });
1289        },
1290        getTime: function() {
1291          return $http({
1292                   method: 'GET',
1293                   url: DataService.getHost() +
1294                       '/xyz/openbmc_project/time/enumerate',
1295                   withCredentials: true
1296                 })
1297              .then(function(response) {
1298                return response.data;
1299              });
1300        },
1301        // Even though NTPServers is a network interface specific path
1302        // (e.g. /xyz/openbmc_project/network/eth0/attr/NTPServers) it acts
1303        // like a global setting. Just use eth0 for setting and getting the
1304        // NTP Servers until it is moved to a non-network interface specific
1305        // path like it is in Redfish. TODO: openbmc/phosphor-time-manager#4
1306        getNTPServers: function() {
1307          return $http({
1308                   method: 'GET',
1309                   url: DataService.getHost() +
1310                       '/xyz/openbmc_project/network/eth0/attr/NTPServers',
1311                   withCredentials: true
1312                 })
1313              .then(function(response) {
1314                return response.data;
1315              });
1316        },
1317        setNTPServers: function(ntpServers) {
1318          return $http({
1319                   method: 'PUT',
1320                   url: DataService.getHost() +
1321                       '/xyz/openbmc_project/network/eth0/attr/NTPServers',
1322                   withCredentials: true,
1323                   data: JSON.stringify({'data': ntpServers})
1324                 })
1325              .then(function(response) {
1326                return response.data;
1327              });
1328        },
1329        setTimeMode: function(timeMode) {
1330          return $http({
1331                   method: 'PUT',
1332                   url: DataService.getHost() +
1333                       '/xyz/openbmc_project/time/sync_method/attr/TimeSyncMethod',
1334                   withCredentials: true,
1335                   data: JSON.stringify({'data': timeMode})
1336                 })
1337              .then(function(response) {
1338                return response.data;
1339              });
1340        },
1341        setTimeOwner: function(timeOwner) {
1342          return $http({
1343                   method: 'PUT',
1344                   url: DataService.getHost() +
1345                       '/xyz/openbmc_project/time/owner/attr/TimeOwner',
1346                   withCredentials: true,
1347                   data: JSON.stringify({'data': timeOwner})
1348                 })
1349              .then(function(response) {
1350                return response.data;
1351              });
1352        },
1353        setBMCTime: function(time) {
1354          return $http({
1355                   method: 'PUT',
1356                   url: DataService.getHost() +
1357                       '/xyz/openbmc_project/time/bmc/attr/Elapsed',
1358                   withCredentials: true,
1359                   data: JSON.stringify({'data': time})
1360                 })
1361              .then(function(response) {
1362                return response.data;
1363              });
1364        },
1365        setHostTime: function(time) {
1366          return $http({
1367                   method: 'PUT',
1368                   url: DataService.getHost() +
1369                       '/xyz/openbmc_project/time/host/attr/Elapsed',
1370                   withCredentials: true,
1371                   data: JSON.stringify({'data': time})
1372                 })
1373              .then(function(response) {
1374                return response.data;
1375              });
1376        },
1377        getHardwares: function(callback) {
1378          $http({
1379            method: 'GET',
1380            url: DataService.getHost() +
1381                '/xyz/openbmc_project/inventory/enumerate',
1382            withCredentials: true
1383          }).then(function(response) {
1384            var json = JSON.stringify(response.data);
1385            var content = JSON.parse(json);
1386            var hardwareData = [];
1387            var keyIndexMap = {};
1388            var title = '';
1389            var depth = '';
1390            var data = [];
1391            var searchText = '';
1392            var componentIndex = -1;
1393            var parent = '';
1394
1395            function isSubComponent(key) {
1396              for (var i = 0; i < Constants.HARDWARE.parent_components.length;
1397                   i++) {
1398                if (key.split(Constants.HARDWARE.parent_components[i]).length ==
1399                    2)
1400                  return true;
1401              }
1402
1403              return false;
1404            }
1405
1406            function titlelize(title) {
1407              title = title.replace(/([A-Z0-9]+)/g, ' $1').replace(/^\s+/, '');
1408              for (var i = 0; i < Constants.HARDWARE.uppercase_titles.length;
1409                   i++) {
1410                if (title.toLowerCase().indexOf(
1411                        (Constants.HARDWARE.uppercase_titles[i] + ' ')) > -1) {
1412                  return title.toUpperCase();
1413                }
1414              }
1415
1416              return title;
1417            }
1418
1419            function camelcaseToLabel(obj) {
1420              var transformed = [], label = '', value = '';
1421              for (var key in obj) {
1422                label = key.replace(/([A-Z0-9]+)/g, ' $1').replace(/^\s+/, '');
1423                if (obj[key] !== '') {
1424                  value = obj[key];
1425                  if (value == 1 || value == 0) {
1426                    value = (value == 1) ? 'Yes' : 'No';
1427                  }
1428                  transformed.push({key: label, value: value});
1429                }
1430              }
1431
1432              return transformed;
1433            }
1434
1435            function determineParent(key) {
1436              var levels = key.split('/');
1437              levels.pop();
1438              return levels.join('/');
1439            }
1440
1441            function getSearchText(data) {
1442              var searchText = '';
1443              for (var i = 0; i < data.length; i++) {
1444                searchText += ' ' + data[i].key + ' ' + data[i].value;
1445              }
1446
1447              return searchText;
1448            }
1449
1450            for (var key in content.data) {
1451              if (content.data.hasOwnProperty(key) &&
1452                  key.indexOf(Constants.HARDWARE.component_key_filter) == 0) {
1453                data = camelcaseToLabel(content.data[key]);
1454                searchText = getSearchText(data);
1455                title = key.split('/').pop();
1456                // All and only associations have the property "endpoints".
1457                // We don't want to show associations on the hardware page.
1458                // Example: An association from the BMC inventory item to the
1459                // BMC firmware images.
1460                if (content.data[key].hasOwnProperty('endpoints')) {
1461                  continue;
1462                }
1463
1464                title = titlelize(title);
1465                // e.g. /xyz/openbmc_project/inventory/system and
1466                // /xyz/openbmc_project/inventory/system/chassis are depths of 5
1467                // and 6.
1468                depth = key.split('/').length;
1469                parent = determineParent(key);
1470
1471                if (!isSubComponent(key)) {
1472                  hardwareData.push(Object.assign(
1473                      {
1474                        path: key,
1475                        title: title,
1476                        depth: depth,
1477                        parent: parent,
1478                        selected: false,
1479                        expanded: false,
1480                        search_text: title.toLowerCase() + ' ' +
1481                            searchText.toLowerCase(),
1482                        sub_components: [],
1483                        original_data: {key: key, value: content.data[key]}
1484                      },
1485                      {items: data}));
1486
1487                  keyIndexMap[key] = hardwareData.length - 1;
1488                } else {
1489                  parent = determineParent(key)
1490                  componentIndex = keyIndexMap[parent];
1491                  data = content.data[key];
1492                  data.title = title;
1493                  hardwareData[componentIndex].sub_components.push(data);
1494                  hardwareData[componentIndex].search_text +=
1495                      ' ' + title.toLowerCase();
1496
1497                  // Sort the subcomponents alphanumeric so they are displayed
1498                  // on the inventory page in order (e.g. core 0, core 1, core
1499                  // 2, ... core 12, core 13)
1500                  hardwareData[componentIndex].sub_components.sort(function(
1501                      a, b) {
1502                    return a.title.localeCompare(
1503                        b.title, 'en', {numeric: true});
1504                  });
1505                }
1506              }
1507            }
1508            // First, order the components by depth and then place the child
1509            // components beneath their parent component alphanumerically. Can
1510            // be removed with completion of
1511            // https://github.com/openbmc/openbmc/issues/3401
1512            // TODO: Remove this once implemented in back end
1513            hardwareData.sort(function(a, b) {
1514              if (a.depth < b.depth) return -1;
1515              if (a.depth > b.depth) return 1;
1516              return b.title.localeCompare(a.title, 'en', {numeric: true});
1517            });
1518
1519            var orderedComponents = [];
1520
1521            for (var i = 0; i < hardwareData.length; i++) {
1522              if (!keyIndexMap[hardwareData[i].parent]) {
1523                orderedComponents.push(hardwareData[i]);
1524              } else {
1525                for (var j = 0; j < orderedComponents.length; j++) {
1526                  if (orderedComponents[j].path === hardwareData[i].parent) {
1527                    var child = hardwareData[i];
1528                    orderedComponents.splice(j + 1, 0, child);
1529                  }
1530                }
1531              }
1532            }
1533
1534            if (callback) {
1535              callback(orderedComponents, content.data);
1536            } else {
1537              return {data: orderedComponents, original_data: content.data};
1538            }
1539          });
1540        },
1541        deleteLogs: function(logs) {
1542          var defer = $q.defer();
1543          var promises = [];
1544
1545          function finished() {
1546            defer.resolve();
1547          }
1548
1549          logs.forEach(function(item) {
1550            promises.push($http({
1551              method: 'POST',
1552              url: DataService.getHost() +
1553                  '/xyz/openbmc_project/logging/entry/' + item.Id +
1554                  '/action/Delete',
1555              withCredentials: true,
1556              data: JSON.stringify({'data': []})
1557            }));
1558          });
1559
1560          $q.all(promises).then(finished);
1561
1562          return defer.promise;
1563        },
1564        resolveLogs: function(logs) {
1565          var promises = [];
1566
1567          logs.forEach(function(item) {
1568            promises.push($http({
1569              method: 'PUT',
1570              url: DataService.getHost() +
1571                  '/xyz/openbmc_project/logging/entry/' + item.Id +
1572                  '/attr/Resolved',
1573              withCredentials: true,
1574              data: JSON.stringify({'data': true})
1575            }));
1576          });
1577          return $q.all(promises);
1578        },
1579        getPowerConsumption: function() {
1580          return $http({
1581                   method: 'GET',
1582                   url: DataService.getHost() +
1583                       '/xyz/openbmc_project/sensors/power/total_power',
1584                   withCredentials: true
1585                 })
1586              .then(
1587                  function(response) {
1588                    var json = JSON.stringify(response.data);
1589                    var content = JSON.parse(json);
1590
1591                    return getScaledValue(
1592                               content.data.Value, content.data.Scale) +
1593                        ' ' +
1594                        Constants.POWER_CONSUMPTION_TEXT[content.data.Unit];
1595                  },
1596                  function(error) {
1597                    if ('Not Found' == error.statusText) {
1598                      return Constants.POWER_CONSUMPTION_TEXT.notavailable;
1599                    } else {
1600                      throw error;
1601                    }
1602                  });
1603        },
1604        getPowerCap: function() {
1605          return $http({
1606                   method: 'GET',
1607                   url: DataService.getHost() +
1608                       '/xyz/openbmc_project/control/host0/power_cap',
1609                   withCredentials: true
1610                 })
1611              .then(function(response) {
1612                return response.data;
1613              });
1614        },
1615        setPowerCapEnable: function(powerCapEnable) {
1616          return $http({
1617                   method: 'PUT',
1618                   url: DataService.getHost() +
1619                       '/xyz/openbmc_project/control/host0/power_cap/attr/PowerCapEnable',
1620                   withCredentials: true,
1621                   data: JSON.stringify({'data': powerCapEnable})
1622                 })
1623              .then(function(response) {
1624                return response.data;
1625              });
1626        },
1627        setPowerCap: function(powerCap) {
1628          return $http({
1629                   method: 'PUT',
1630                   url: DataService.getHost() +
1631                       '/xyz/openbmc_project/control/host0/power_cap/attr/PowerCap',
1632                   withCredentials: true,
1633                   data: JSON.stringify({'data': powerCap})
1634                 })
1635              .then(function(response) {
1636                return response.data;
1637              });
1638        },
1639        setHostname: function(hostname) {
1640          return $http({
1641                   method: 'PUT',
1642                   url: DataService.getHost() +
1643                       '/xyz/openbmc_project/network/config/attr/HostName',
1644                   withCredentials: true,
1645                   data: JSON.stringify({'data': hostname})
1646                 })
1647              .then(function(response) {
1648                return response.data;
1649              });
1650        },
1651      };
1652      return SERVICE;
1653    }
1654  ]);
1655})(window.angular);
1656