...
1
18
19 package service_learning
20
21 import (
22 "fmt"
23 "io/ioutil"
24 "scheduler/log"
25 "scheduler/utils"
26 "strconv"
27 )
28
29 const headerLearningEid = "X-P2pfaas-Learning-Eid"
30 const headerLearningState = "X-P2pfaas-Learning-State"
31 const headerLearningAction = "X-P2pfaas-Learning-Action"
32 const headerLearningReward = "X-P2pfaas-Learning-Reward"
33
34 const headerEpsilon = "X-P2pfaas-Eps"
35
36 func Act(entry *EntryAct) (*EntryActOutput, error) {
37 var err error
38 actOutput := EntryActOutput{}
39
40 headers := []utils.HttpHeader{
41 {Key: headerLearningState, Value: prepareStateString(entry.State)},
42 }
43 res, err := utils.HttpGetWithHeaders(getApiUrlAct(), headers)
44 if err != nil {
45 log.Log.Error("Cannot get the action from learning service at %s", getApiUrlAct())
46 return nil, err
47 }
48
49 response, _ := ioutil.ReadAll(res.Body)
50 _ = res.Body.Close()
51
52
53 responseString := string(response)
54 actOutput.Action, err = strconv.ParseFloat(responseString, 64)
55 if err != nil {
56 return nil, err
57 }
58
59
60 eps := res.Header.Get(headerEpsilon)
61 if eps != "" {
62 actOutput.Eps, err = strconv.ParseFloat(eps, 64)
63 }
64
65 return &actOutput, nil
66 }
67
68 func Train(entry *EntryLearning) error {
69 headers := []utils.HttpHeader{
70 {Key: headerLearningEid, Value: fmt.Sprintf("%d", entry.Eid)},
71 {Key: headerLearningState, Value: prepareStateString(entry.State)},
72 {Key: headerLearningAction, Value: fmt.Sprintf("%.4f", entry.Action)},
73 {Key: headerLearningReward, Value: fmt.Sprintf("%.4f", entry.Reward)},
74 }
75 res, err := utils.HttpGetWithHeaders(getApiUrlTrain(), headers)
76 if err != nil {
77 log.Log.Error("Cannot get the action from learning service at %s", getApiUrlTrain())
78 return err
79 }
80
81 if res.StatusCode != 200 {
82 return fmt.Errorf("failed train call")
83 }
84
85 return nil
86 }
87
View as plain text