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