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        getLastPowerTime: function() {
802          return $http({
803                   method: 'GET',
804                   url: DataService.getHost() +
805                       '/xyz/openbmc_project/state/chassis0/attr/LastStateChangeTime',
806                   withCredentials: true
807                 })
808              .then(function(response) {
809                return response.data;
810              });
811        },
812        getLogs: function() {
813          var deferred = $q.defer();
814          $http({
815            method: 'GET',
816            url: DataService.getHost() +
817                '/xyz/openbmc_project/logging/enumerate',
818            withCredentials: true
819          })
820              .then(
821                  function(response) {
822                    var json = JSON.stringify(response.data);
823                    var content = JSON.parse(json);
824                    var dataClone = JSON.parse(JSON.stringify(content.data));
825                    var data = [];
826                    var severityCode = '';
827                    var priority = '';
828                    var health = '';
829                    var relatedItems = [];
830                    var eventID = 'None';
831                    var description = 'None';
832
833                    for (var key in content.data) {
834                      if (content.data.hasOwnProperty(key) &&
835                          content.data[key].hasOwnProperty('Id')) {
836                        var severityFlags = {
837                          low: false,
838                          medium: false,
839                          high: false
840                        };
841                        severityCode =
842                            content.data[key].Severity.split('.').pop();
843                        priority =
844                            Constants.SEVERITY_TO_PRIORITY_MAP[severityCode];
845                        severityFlags[priority.toLowerCase()] = true;
846                        relatedItems = [];
847                        content.data[key].associations.forEach(function(item) {
848                          relatedItems.push(item[2]);
849                        });
850
851                        if (content.data[key].hasOwnProperty(['EventID'])) {
852                          eventID = content.data[key].EventID;
853                        }
854
855                        if (content.data[key].hasOwnProperty(['Description'])) {
856                          description = content.data[key].Description;
857                        }
858
859                        data.push(Object.assign(
860                            {
861                              path: key,
862                              copied: false,
863                              priority: priority,
864                              severity_code: severityCode,
865                              severity_flags: severityFlags,
866                              additional_data:
867                                  content.data[key].AdditionalData.join('\n'),
868                              type: content.data[key].Message,
869                              selected: false,
870                              search_text:
871                                  ('#' + content.data[key].Id + ' ' +
872                                   severityCode + ' ' +
873                                   content.data[key].Message + ' ' +
874                                   content.data[key].Severity + ' ' +
875                                   content.data[key].AdditionalData.join(' '))
876                                      .toLowerCase(),
877                              meta: false,
878                              confirm: false,
879                              related_items: relatedItems,
880                              eventID: eventID,
881                              description: description,
882                              data: {key: key, value: content.data[key]}
883                            },
884                            content.data[key]));
885                      }
886                    }
887                    deferred.resolve({data: data, original: dataClone});
888                  },
889                  function(error) {
890                    console.log(error);
891                    deferred.reject(error);
892                  });
893
894          return deferred.promise;
895        },
896        getAllSensorStatus: function(callback) {
897          $http({
898            method: 'GET',
899            url: DataService.getHost() +
900                '/xyz/openbmc_project/sensors/enumerate',
901            withCredentials: true
902          })
903              .then(
904                  function(response) {
905                    var json = JSON.stringify(response.data);
906                    var content = JSON.parse(json);
907                    var dataClone = JSON.parse(JSON.stringify(content.data));
908                    var sensorData = [];
909                    var severity = {};
910                    var title = '';
911                    var tempKeyParts = [];
912                    var order = 0;
913                    var customOrder = 0;
914
915                    function getSensorStatus(reading) {
916                      var severityFlags = {
917                        critical: false,
918                        warning: false,
919                        normal: false
920                      },
921                          severityText = '', order = 0;
922
923                      if (reading.hasOwnProperty('CriticalLow') &&
924                          reading.Value < reading.CriticalLow) {
925                        severityFlags.critical = true;
926                        severityText = 'critical';
927                        order = 2;
928                      } else if (
929                          reading.hasOwnProperty('CriticalHigh') &&
930                          reading.Value > reading.CriticalHigh) {
931                        severityFlags.critical = true;
932                        severityText = 'critical';
933                        order = 2;
934                      } else if (
935                          reading.hasOwnProperty('CriticalLow') &&
936                          reading.hasOwnProperty('WarningLow') &&
937                          reading.Value >= reading.CriticalLow &&
938                          reading.Value <= reading.WarningLow) {
939                        severityFlags.warning = true;
940                        severityText = 'warning';
941                        order = 1;
942                      } else if (
943                          reading.hasOwnProperty('WarningHigh') &&
944                          reading.hasOwnProperty('CriticalHigh') &&
945                          reading.Value >= reading.WarningHigh &&
946                          reading.Value <= reading.CriticalHigh) {
947                        severityFlags.warning = true;
948                        severityText = 'warning';
949                        order = 1;
950                      } else {
951                        severityFlags.normal = true;
952                        severityText = 'normal';
953                      }
954                      return {
955                        flags: severityFlags,
956                        severityText: severityText,
957                        order: order
958                      };
959                    }
960
961                    for (var key in content.data) {
962                      if (content.data.hasOwnProperty(key) &&
963                          content.data[key].hasOwnProperty('Unit')) {
964                        severity = getSensorStatus(content.data[key]);
965
966                        if (!content.data[key].hasOwnProperty('CriticalLow')) {
967                          content.data[key].CriticalLow = '--';
968                          content.data[key].CriticalHigh = '--';
969                        }
970
971                        if (!content.data[key].hasOwnProperty('WarningLow')) {
972                          content.data[key].WarningLow = '--';
973                          content.data[key].WarningHigh = '--';
974                        }
975
976                        tempKeyParts = key.split('/');
977                        title = tempKeyParts.pop();
978                        title = tempKeyParts.pop() + '_' + title;
979                        title = title.split('_')
980                                    .map(function(item) {
981                                      return item.toLowerCase()
982                                                 .charAt(0)
983                                                 .toUpperCase() +
984                                          item.slice(1);
985                                    })
986                                    .reduce(function(prev, el) {
987                                      return prev + ' ' + el;
988                                    });
989
990                        content.data[key].Value = getScaledValue(
991                            content.data[key].Value, content.data[key].Scale);
992                        content.data[key].CriticalLow = getScaledValue(
993                            content.data[key].CriticalLow,
994                            content.data[key].Scale);
995                        content.data[key].CriticalHigh = getScaledValue(
996                            content.data[key].CriticalHigh,
997                            content.data[key].Scale);
998                        content.data[key].WarningLow = getScaledValue(
999                            content.data[key].WarningLow,
1000                            content.data[key].Scale);
1001                        content.data[key].WarningHigh = getScaledValue(
1002                            content.data[key].WarningHigh,
1003                            content.data[key].Scale);
1004                        if (Constants.SENSOR_SORT_ORDER.indexOf(
1005                                content.data[key].Unit) > -1) {
1006                          customOrder = Constants.SENSOR_SORT_ORDER.indexOf(
1007                              content.data[key].Unit);
1008                        } else {
1009                          customOrder = Constants.SENSOR_SORT_ORDER_DEFAULT;
1010                        }
1011
1012                        sensorData.push(Object.assign(
1013                            {
1014                              path: key,
1015                              selected: false,
1016                              confirm: false,
1017                              copied: false,
1018                              title: title,
1019                              unit:
1020                                  Constants
1021                                      .SENSOR_UNIT_MAP[content.data[key].Unit],
1022                              severity_flags: severity.flags,
1023                              status: severity.severityText,
1024                              order: severity.order,
1025                              custom_order: customOrder,
1026                              search_text:
1027                                  (title + ' ' + content.data[key].Value + ' ' +
1028                                   Constants.SENSOR_UNIT_MAP[content.data[key]
1029                                                                 .Unit] +
1030                                   ' ' + severity.severityText + ' ' +
1031                                   content.data[key].CriticalLow + ' ' +
1032                                   content.data[key].CriticalHigh + ' ' +
1033                                   content.data[key].WarningLow + ' ' +
1034                                   content.data[key].WarningHigh + ' ')
1035                                      .toLowerCase(),
1036                              original_data:
1037                                  {key: key, value: content.data[key]}
1038                            },
1039                            content.data[key]));
1040                      }
1041                    }
1042
1043                    callback(sensorData, dataClone);
1044                  },
1045                  function(error) {
1046                    console.log(error);
1047                  });
1048        },
1049        getActivation: function(imageId) {
1050          return $http({
1051                   method: 'GET',
1052                   url: DataService.getHost() +
1053                       '/xyz/openbmc_project/software/' + imageId +
1054                       '/attr/Activation',
1055                   withCredentials: true
1056                 })
1057              .then(function(response) {
1058                return response.data;
1059              });
1060        },
1061        getFirmwares: function() {
1062          var deferred = $q.defer();
1063          $http({
1064            method: 'GET',
1065            url: DataService.getHost() +
1066                '/xyz/openbmc_project/software/enumerate',
1067            withCredentials: true
1068          })
1069              .then(
1070                  function(response) {
1071                    var json = JSON.stringify(response.data);
1072                    var content = JSON.parse(json);
1073                    var data = [];
1074                    var isExtended = false;
1075                    var bmcActiveVersion = '';
1076                    var hostActiveVersion = '';
1077                    var imageType = '';
1078                    var extendedVersions = [];
1079                    var functionalImages = [];
1080
1081                    function getFormatedExtendedVersions(extendedVersion) {
1082                      var versions = [];
1083                      extendedVersion = extendedVersion.split(',');
1084
1085                      extendedVersion.forEach(function(item) {
1086                        var parts = item.split('-');
1087                        var numberIndex = 0;
1088                        for (var i = 0; i < parts.length; i++) {
1089                          if (/[0-9]/.test(parts[i])) {
1090                            numberIndex = i;
1091                            break;
1092                          }
1093                        }
1094                        var titlePart = parts.splice(0, numberIndex);
1095                        titlePart = titlePart.join('');
1096                        titlePart = titlePart[0].toUpperCase() +
1097                            titlePart.substr(1, titlePart.length);
1098                        var versionPart = parts.join('-');
1099                        versions.push({title: titlePart, version: versionPart});
1100                      });
1101
1102                      return versions;
1103                    }
1104
1105                    // Get the list of functional images so we can compare
1106                    // later if an image is functional
1107                    if (content.data[Constants.FIRMWARE.FUNCTIONAL_OBJPATH]) {
1108                      functionalImages =
1109                          content.data[Constants.FIRMWARE.FUNCTIONAL_OBJPATH]
1110                              .endpoints;
1111                    }
1112                    for (var key in content.data) {
1113                      if (content.data.hasOwnProperty(key) &&
1114                          content.data[key].hasOwnProperty('Version')) {
1115                        var activationStatus = '';
1116
1117                        // If the image is "Functional" use that for the
1118                        // activation status, else use the value of
1119                        // "Activation"
1120                        // github.com/openbmc/phosphor-dbus-interfaces/blob/master/xyz/openbmc_project/Software/Activation.interface.yaml
1121                        if (content.data[key].Activation) {
1122                          activationStatus =
1123                              content.data[key].Activation.split('.').pop();
1124                        }
1125
1126                        if (functionalImages.includes(key)) {
1127                          activationStatus = 'Functional';
1128                        }
1129
1130                        imageType = content.data[key].Purpose.split('.').pop();
1131                        isExtended = content.data[key].hasOwnProperty(
1132                                         'ExtendedVersion') &&
1133                            content.data[key].ExtendedVersion != '';
1134                        if (isExtended) {
1135                          extendedVersions = getFormatedExtendedVersions(
1136                              content.data[key].ExtendedVersion);
1137                        }
1138                        data.push(Object.assign(
1139                            {
1140                              path: key,
1141                              activationStatus: activationStatus,
1142                              imageId: key.split('/').pop(),
1143                              imageType: imageType,
1144                              isExtended: isExtended,
1145                              extended:
1146                                  {show: false, versions: extendedVersions},
1147                              data: {key: key, value: content.data[key]}
1148                            },
1149                            content.data[key]));
1150
1151                        if (activationStatus == 'Functional' &&
1152                            imageType == 'BMC') {
1153                          bmcActiveVersion = content.data[key].Version;
1154                        }
1155
1156                        if (activationStatus == 'Functional' &&
1157                            imageType == 'Host') {
1158                          hostActiveVersion = content.data[key].Version;
1159                        }
1160                      }
1161                    }
1162
1163                    deferred.resolve({
1164                      data: data,
1165                      bmcActiveVersion: bmcActiveVersion,
1166                      hostActiveVersion: hostActiveVersion
1167                    });
1168                  },
1169                  function(error) {
1170                    console.log(error);
1171                    deferred.reject(error);
1172                  });
1173
1174          return deferred.promise;
1175        },
1176        changePriority: function(imageId, priority) {
1177          return $http({
1178                   method: 'PUT',
1179                   url: DataService.getHost() +
1180                       '/xyz/openbmc_project/software/' + imageId +
1181                       '/attr/Priority',
1182                   withCredentials: true,
1183                   data: JSON.stringify({'data': priority})
1184                 })
1185              .then(function(response) {
1186                return response.data;
1187              });
1188        },
1189        deleteImage: function(imageId) {
1190          return $http({
1191                   method: 'POST',
1192                   url: DataService.getHost() +
1193                       '/xyz/openbmc_project/software/' + imageId +
1194                       '/action/Delete',
1195                   withCredentials: true,
1196                   data: JSON.stringify({'data': []})
1197                 })
1198              .then(function(response) {
1199                return response.data;
1200              });
1201        },
1202        activateImage: function(imageId) {
1203          return $http({
1204                   method: 'PUT',
1205                   url: DataService.getHost() +
1206                       '/xyz/openbmc_project/software/' + imageId +
1207                       '/attr/RequestedActivation',
1208                   withCredentials: true,
1209                   data: JSON.stringify(
1210                       {'data': Constants.FIRMWARE.ACTIVATE_FIRMWARE})
1211                 })
1212              .then(function(response) {
1213                return response.data;
1214              });
1215        },
1216        uploadImage: function(file) {
1217          return $http({
1218                   method: 'POST',
1219                   timeout: 5 * 60 * 1000,
1220                   url: DataService.getHost() + '/upload/image',
1221                   // Overwrite the default 'application/json' Content-Type
1222                   headers: {'Content-Type': 'application/octet-stream'},
1223                   withCredentials: true,
1224                   data: file
1225                 })
1226              .then(function(response) {
1227                return response.data;
1228              });
1229        },
1230        downloadImage: function(host, filename) {
1231          return $http({
1232                   method: 'POST',
1233                   url: DataService.getHost() +
1234                       '/xyz/openbmc_project/software/action/DownloadViaTFTP',
1235                   withCredentials: true,
1236                   data: JSON.stringify({'data': [filename, host]}),
1237                   responseType: 'arraybuffer'
1238                 })
1239              .then(function(response) {
1240                return response.data;
1241              });
1242        },
1243        getServerInfo: function() {
1244          // TODO: openbmc/openbmc#3117 Need a way via REST to get
1245          // interfaces so we can get the system object(s) by the looking
1246          // for the system interface.
1247          return $http({
1248                   method: 'GET',
1249                   url: DataService.getHost() +
1250                       '/xyz/openbmc_project/inventory/system',
1251                   withCredentials: true
1252                 })
1253              .then(function(response) {
1254                return response.data;
1255              });
1256        },
1257        getBMCTime: function() {
1258          return $http({
1259                   method: 'GET',
1260                   url: DataService.getHost() + '/xyz/openbmc_project/time/bmc',
1261                   withCredentials: true
1262                 })
1263              .then(function(response) {
1264                return response.data;
1265              });
1266        },
1267        getTime: function() {
1268          return $http({
1269                   method: 'GET',
1270                   url: DataService.getHost() +
1271                       '/xyz/openbmc_project/time/enumerate',
1272                   withCredentials: true
1273                 })
1274              .then(function(response) {
1275                return response.data;
1276              });
1277        },
1278        // Even though NTPServers is a network interface specific path
1279        // (e.g. /xyz/openbmc_project/network/eth0/attr/NTPServers) it acts
1280        // like a global setting. Just use eth0 for setting and getting the
1281        // NTP Servers until it is moved to a non-network interface specific
1282        // path like it is in Redfish. TODO: openbmc/phosphor-time-manager#4
1283        getNTPServers: function() {
1284          return $http({
1285                   method: 'GET',
1286                   url: DataService.getHost() +
1287                       '/xyz/openbmc_project/network/eth0/attr/NTPServers',
1288                   withCredentials: true
1289                 })
1290              .then(function(response) {
1291                return response.data;
1292              });
1293        },
1294        setNTPServers: function(ntpServers) {
1295          return $http({
1296                   method: 'PUT',
1297                   url: DataService.getHost() +
1298                       '/xyz/openbmc_project/network/eth0/attr/NTPServers',
1299                   withCredentials: true,
1300                   data: JSON.stringify({'data': ntpServers})
1301                 })
1302              .then(function(response) {
1303                return response.data;
1304              });
1305        },
1306        setTimeMode: function(timeMode) {
1307          return $http({
1308                   method: 'PUT',
1309                   url: DataService.getHost() +
1310                       '/xyz/openbmc_project/time/sync_method/attr/TimeSyncMethod',
1311                   withCredentials: true,
1312                   data: JSON.stringify({'data': timeMode})
1313                 })
1314              .then(function(response) {
1315                return response.data;
1316              });
1317        },
1318        setTimeOwner: function(timeOwner) {
1319          return $http({
1320                   method: 'PUT',
1321                   url: DataService.getHost() +
1322                       '/xyz/openbmc_project/time/owner/attr/TimeOwner',
1323                   withCredentials: true,
1324                   data: JSON.stringify({'data': timeOwner})
1325                 })
1326              .then(function(response) {
1327                return response.data;
1328              });
1329        },
1330        setBMCTime: function(time) {
1331          return $http({
1332                   method: 'PUT',
1333                   url: DataService.getHost() +
1334                       '/xyz/openbmc_project/time/bmc/attr/Elapsed',
1335                   withCredentials: true,
1336                   data: JSON.stringify({'data': time})
1337                 })
1338              .then(function(response) {
1339                return response.data;
1340              });
1341        },
1342        setHostTime: function(time) {
1343          return $http({
1344                   method: 'PUT',
1345                   url: DataService.getHost() +
1346                       '/xyz/openbmc_project/time/host/attr/Elapsed',
1347                   withCredentials: true,
1348                   data: JSON.stringify({'data': time})
1349                 })
1350              .then(function(response) {
1351                return response.data;
1352              });
1353        },
1354        getHardwares: function(callback) {
1355          $http({
1356            method: 'GET',
1357            url: DataService.getHost() +
1358                '/xyz/openbmc_project/inventory/enumerate',
1359            withCredentials: true
1360          }).then(function(response) {
1361            var json = JSON.stringify(response.data);
1362            var content = JSON.parse(json);
1363            var hardwareData = [];
1364            var keyIndexMap = {};
1365            var title = '';
1366            var depth = '';
1367            var data = [];
1368            var searchText = '';
1369            var componentIndex = -1;
1370            var parent = '';
1371
1372            function isSubComponent(key) {
1373              for (var i = 0; i < Constants.HARDWARE.parent_components.length;
1374                   i++) {
1375                if (key.split(Constants.HARDWARE.parent_components[i]).length ==
1376                    2)
1377                  return true;
1378              }
1379
1380              return false;
1381            }
1382
1383            function titlelize(title) {
1384              title = title.replace(/([A-Z0-9]+)/g, ' $1').replace(/^\s+/, '');
1385              for (var i = 0; i < Constants.HARDWARE.uppercase_titles.length;
1386                   i++) {
1387                if (title.toLowerCase().indexOf(
1388                        (Constants.HARDWARE.uppercase_titles[i] + ' ')) > -1) {
1389                  return title.toUpperCase();
1390                }
1391              }
1392
1393              return title;
1394            }
1395
1396            function camelcaseToLabel(obj) {
1397              var transformed = [], label = '', value = '';
1398              for (var key in obj) {
1399                label = key.replace(/([A-Z0-9]+)/g, ' $1').replace(/^\s+/, '');
1400                if (obj[key] !== '') {
1401                  value = obj[key];
1402                  if (value == 1 || value == 0) {
1403                    value = (value == 1) ? 'Yes' : 'No';
1404                  }
1405                  transformed.push({key: label, value: value});
1406                }
1407              }
1408
1409              return transformed;
1410            }
1411
1412            function determineParent(key) {
1413              var levels = key.split('/');
1414              levels.pop();
1415              return levels.join('/');
1416            }
1417
1418            function getSearchText(data) {
1419              var searchText = '';
1420              for (var i = 0; i < data.length; i++) {
1421                searchText += ' ' + data[i].key + ' ' + data[i].value;
1422              }
1423
1424              return searchText;
1425            }
1426
1427            for (var key in content.data) {
1428              if (content.data.hasOwnProperty(key) &&
1429                  key.indexOf(Constants.HARDWARE.component_key_filter) == 0) {
1430                data = camelcaseToLabel(content.data[key]);
1431                searchText = getSearchText(data);
1432                title = key.split('/').pop();
1433                // All and only associations have the property "endpoints".
1434                // We don't want to show associations on the hardware page.
1435                // Example: An association from the BMC inventory item to the
1436                // BMC firmware images.
1437                if (content.data[key].hasOwnProperty('endpoints')) {
1438                  continue;
1439                }
1440
1441                title = titlelize(title);
1442                // e.g. /xyz/openbmc_project/inventory/system and
1443                // /xyz/openbmc_project/inventory/system/chassis are depths of 5
1444                // and 6.
1445                depth = key.split('/').length;
1446                parent = determineParent(key);
1447
1448                if (!isSubComponent(key)) {
1449                  hardwareData.push(Object.assign(
1450                      {
1451                        path: key,
1452                        title: title,
1453                        depth: depth,
1454                        parent: parent,
1455                        selected: false,
1456                        expanded: false,
1457                        search_text: title.toLowerCase() + ' ' +
1458                            searchText.toLowerCase(),
1459                        sub_components: [],
1460                        original_data: {key: key, value: content.data[key]}
1461                      },
1462                      {items: data}));
1463
1464                  keyIndexMap[key] = hardwareData.length - 1;
1465                } else {
1466                  parent = determineParent(key)
1467                  componentIndex = keyIndexMap[parent];
1468                  data = content.data[key];
1469                  data.title = title;
1470                  hardwareData[componentIndex].sub_components.push(data);
1471                  hardwareData[componentIndex].search_text +=
1472                      ' ' + title.toLowerCase();
1473
1474                  // Sort the subcomponents alphanumeric so they are displayed
1475                  // on the inventory page in order (e.g. core 0, core 1, core
1476                  // 2, ... core 12, core 13)
1477                  hardwareData[componentIndex].sub_components.sort(function(
1478                      a, b) {
1479                    return a.title.localeCompare(
1480                        b.title, 'en', {numeric: true});
1481                  });
1482                }
1483              }
1484            }
1485            // First, order the components by depth and then place the child
1486            // components beneath their parent component alphanumerically. Can
1487            // be removed with completion of
1488            // https://github.com/openbmc/openbmc/issues/3401
1489            // TODO: Remove this once implemented in back end
1490            hardwareData.sort(function(a, b) {
1491              if (a.depth < b.depth) return -1;
1492              if (a.depth > b.depth) return 1;
1493              return b.title.localeCompare(a.title, 'en', {numeric: true});
1494            });
1495
1496            var orderedComponents = [];
1497
1498            for (var i = 0; i < hardwareData.length; i++) {
1499              if (!keyIndexMap[hardwareData[i].parent]) {
1500                orderedComponents.push(hardwareData[i]);
1501              } else {
1502                for (var j = 0; j < orderedComponents.length; j++) {
1503                  if (orderedComponents[j].path === hardwareData[i].parent) {
1504                    var child = hardwareData[i];
1505                    orderedComponents.splice(j + 1, 0, child);
1506                  }
1507                }
1508              }
1509            }
1510
1511            if (callback) {
1512              callback(orderedComponents, content.data);
1513            } else {
1514              return {data: orderedComponents, original_data: content.data};
1515            }
1516          });
1517        },
1518        deleteLogs: function(logs) {
1519          var defer = $q.defer();
1520          var promises = [];
1521
1522          function finished() {
1523            defer.resolve();
1524          }
1525
1526          logs.forEach(function(item) {
1527            promises.push($http({
1528              method: 'POST',
1529              url: DataService.getHost() +
1530                  '/xyz/openbmc_project/logging/entry/' + item.Id +
1531                  '/action/Delete',
1532              withCredentials: true,
1533              data: JSON.stringify({'data': []})
1534            }));
1535          });
1536
1537          $q.all(promises).then(finished);
1538
1539          return defer.promise;
1540        },
1541        resolveLogs: function(logs) {
1542          var promises = [];
1543
1544          logs.forEach(function(item) {
1545            promises.push($http({
1546              method: 'PUT',
1547              url: DataService.getHost() +
1548                  '/xyz/openbmc_project/logging/entry/' + item.Id +
1549                  '/attr/Resolved',
1550              withCredentials: true,
1551              data: JSON.stringify({'data': true})
1552            }));
1553          });
1554          return $q.all(promises);
1555        },
1556        getPowerConsumption: function() {
1557          return $http({
1558                   method: 'GET',
1559                   url: DataService.getHost() +
1560                       '/xyz/openbmc_project/sensors/power/total_power',
1561                   withCredentials: true
1562                 })
1563              .then(
1564                  function(response) {
1565                    var json = JSON.stringify(response.data);
1566                    var content = JSON.parse(json);
1567
1568                    return getScaledValue(
1569                               content.data.Value, content.data.Scale) +
1570                        ' ' +
1571                        Constants.POWER_CONSUMPTION_TEXT[content.data.Unit];
1572                  },
1573                  function(error) {
1574                    if ('Not Found' == error.statusText) {
1575                      return Constants.POWER_CONSUMPTION_TEXT.notavailable;
1576                    } else {
1577                      throw error;
1578                    }
1579                  });
1580        },
1581        getPowerCap: function() {
1582          return $http({
1583                   method: 'GET',
1584                   url: DataService.getHost() +
1585                       '/xyz/openbmc_project/control/host0/power_cap',
1586                   withCredentials: true
1587                 })
1588              .then(function(response) {
1589                return response.data;
1590              });
1591        },
1592        setPowerCapEnable: function(powerCapEnable) {
1593          return $http({
1594                   method: 'PUT',
1595                   url: DataService.getHost() +
1596                       '/xyz/openbmc_project/control/host0/power_cap/attr/PowerCapEnable',
1597                   withCredentials: true,
1598                   data: JSON.stringify({'data': powerCapEnable})
1599                 })
1600              .then(function(response) {
1601                return response.data;
1602              });
1603        },
1604        setPowerCap: function(powerCap) {
1605          return $http({
1606                   method: 'PUT',
1607                   url: DataService.getHost() +
1608                       '/xyz/openbmc_project/control/host0/power_cap/attr/PowerCap',
1609                   withCredentials: true,
1610                   data: JSON.stringify({'data': powerCap})
1611                 })
1612              .then(function(response) {
1613                return response.data;
1614              });
1615        },
1616        setHostname: function(hostname) {
1617          return $http({
1618                   method: 'PUT',
1619                   url: DataService.getHost() +
1620                       '/xyz/openbmc_project/network/config/attr/HostName',
1621                   withCredentials: true,
1622                   data: JSON.stringify({'data': hostname})
1623                 })
1624              .then(function(response) {
1625                return response.data;
1626              });
1627        },
1628      };
1629      return SERVICE;
1630    }
1631  ]);
1632})(window.angular);
1633