Debian Codegraph @

server/acceptance/kit/cliloop.go

raw
1 /*
2 Copyright 2013-2014 Canonical Ltd.
3
4 This program is free software: you can redistribute it and/or modify it
5 under the terms of the GNU General Public License version 3, as published
6 by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful, but
9 WITHOUT ANY WARRANTY; without even the implied warranties of
10 MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11 PURPOSE. See the GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License along
14 with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 package kit
18
19 import (
20 "crypto/tls"
21 "flag"
22 "fmt"
23 "log"
24 "os"
25 "path/filepath"
26 "regexp"
27 "strings"
28 "time"
29
30 "gitlab.com/ubports/development/core/lomiri-push-service/external/murmur3"
31
32 "gitlab.com/ubports/development/core/lomiri-push-service/config"
33 "gitlab.com/ubports/development/core/lomiri-push-service/server/acceptance"
34 )
35
36 type Configuration struct {
37 // session configuration
38 ExchangeTimeout config.ConfigTimeDuration `json:"exchange_timeout"`
39 // server connection config
40 Target string `json:"target" help:"production|staging - picks defaults"`
41 Addr config.ConfigHostPort `json:"addr"`
42 Vnode string `json:"vnode" help:"vnode postfix to make up a targeting device-id"`
43 CertPEMFile string `json:"cert_pem_file"`
44 Insecure bool `json:"insecure" help:"disable checking of server certificate and hostname"`
45 Domain string `json:"domain" help:"domain for tls connect"`
46 // api config
47 APIURL string `json:"api" help:"api url"`
48 APICertPEMFile string `json:"api_cert_pem_file"`
49 // run timeout
50 RunTimeout config.ConfigTimeDuration `json:"run_timeout"`
51 // flags
52 ReportPings bool `json:"reportPings" help:"report each Ping from the server"`
53 DeviceModel string `json:"model" help:"device image model"`
54 ImageChannel string `json:"imageChannel" help:"image channel"`
55 BuildNumber int32 `json:"buildNumber" help:"build number"`
56 }
57
58 func (cfg *Configuration) PickByTarget(what, productionValue, stagingValue string) (value string) {
59 switch cfg.Target {
60 case "production":
61 value = productionValue
62 case "staging":
63 value = stagingValue
64 case "":
65 log.Fatalf("either %s or target must be given", what)
66 default:
67 log.Fatalf("if specified target should be production|staging")
68 }
69 return
70 }
71
72 // Control.
73 var (
74 Name = "acceptanceclient"
75 Defaults = map[string]interface{}{
76 "target": "",
77 "addr": ":0",
78 "vnode": "",
79 "exchange_timeout": "5s",
80 "cert_pem_file": "",
81 "insecure": false,
82 "domain": "",
83 "run_timeout": "0s",
84 "reportPings": true,
85 "model": "?",
86 "imageChannel": "?",
87 "buildNumber": -1,
88 "api": "",
89 "api_cert_pem_file": "",
90 }
91 )
92
93 // CliLoop parses command line arguments and runs a client loop.
94 func CliLoop(totalCfg interface{}, cfg *Configuration, onSetup func(sess *acceptance.ClientSession, apiCli *APIClient, cfgDir string), auth func(string) string, waitFor func() string, onConnect func()) {
95 flag.Usage = func() {
96 fmt.Fprintf(os.Stderr, "Usage: %s [options] <device id>\n", Name)
97 flag.PrintDefaults()
98 }
99 missingArg := func(what string) {
100 fmt.Fprintf(os.Stderr, "missing %s\n", what)
101 flag.Usage()
102 os.Exit(2)
103 }
104 err := config.ReadFilesDefaults(totalCfg, Defaults, "<flags>")
105 if err != nil {
106 log.Fatalf("reading config: %v", err)
107 }
108 deviceId := ""
109 if cfg.Vnode != "" {
110 if cfg.Addr == ":0" {
111 log.Fatalf("-vnode needs -addr specified")
112 }
113 deviceId = cfg.Addr.HostPort() + "|" + cfg.Vnode
114 log.Printf("using device-id: %q", deviceId)
115 } else {
116 narg := flag.NArg()
117 switch {
118 case narg < 1:
119 missingArg("device-id")
120 }
121 deviceId = flag.Arg(0)
122 }
123 cfgDir := filepath.Dir(flag.Lookup("cfg@").Value.String())
124 // setup api
125 apiCli := &APIClient{}
126 var apiTLSConfig *tls.Config
127 if cfg.APICertPEMFile != "" || cfg.Insecure {
128 var err error
129 apiTLSConfig, err = MakeTLSConfig("", cfg.Insecure,
130 cfg.APICertPEMFile, cfgDir)
131 if err != nil {
132 log.Fatalf("api tls config: %v", err)
133 }
134 }
135 apiCli.SetupClient(apiTLSConfig, true, 1)
136 if cfg.APIURL == "" {
137 apiCli.ServerAPIURL = cfg.PickByTarget("api",
138 "https://push.ubports.com",
139 "https://push.staging.ubports.com")
140 } else {
141 apiCli.ServerAPIURL = cfg.APIURL
142 }
143 addr := ""
144 domain := ""
145 if cfg.Addr == ":0" {
146 hash := murmur3.Sum64([]byte(deviceId))
147 hosts, err := apiCli.GetRequest("/delivery-hosts",
148 map[string]string{
149 "h": fmt.Sprintf("%x", hash),
150 })
151 if err != nil {
152 log.Fatalf("querying hosts: %v", err)
153 }
154 addr = hosts["hosts"].([]interface{})[0].(string)
155 domain = hosts["domain"].(string)
156 log.Printf("using: %s %s", addr, domain)
157 } else {
158 addr = cfg.Addr.HostPort()
159 domain = cfg.Domain
160 }
161 session := &acceptance.ClientSession{
162 ExchangeTimeout: cfg.ExchangeTimeout.TimeDuration(),
163 ServerAddr: addr,
164 DeviceId: deviceId,
165 // flags
166 Model: cfg.DeviceModel,
167 ImageChannel: cfg.ImageChannel,
168 BuildNumber: cfg.BuildNumber,
169 ReportPings: cfg.ReportPings,
170 }
171 onSetup(session, apiCli, cfgDir)
172 session.TLSConfig, err = MakeTLSConfig(domain, cfg.Insecure, cfg.CertPEMFile, cfgDir)
173 if err != nil {
174 log.Fatalf("tls config: %v", err)
175 }
176 session.Auth = auth("https://push.ubports.com/")
177 var waitForRegexp *regexp.Regexp
178 waitForStr := waitFor()
179 if waitForStr != "" {
180 var err error
181 waitForRegexp, err = regexp.Compile(waitForStr)
182 if err != nil {
183 log.Fatalf("wait_for regexp: %v", err)
184 }
185 }
186 err = session.Dial()
187 if err != nil {
188 log.Fatalln(err)
189 }
190 events := make(chan string, 5)
191 go func() {
192 for {
193 ev := <-events
194 if strings.HasPrefix(ev, "connected") {
195 onConnect()
196 }
197 if waitForRegexp != nil && waitForRegexp.MatchString(ev) {
198 log.Println("<matching-event>:", ev)
199 os.Exit(0)
200 }
201 log.Println(ev)
202 }
203 }()
204 if cfg.RunTimeout.TimeDuration() != 0 {
205 time.AfterFunc(cfg.RunTimeout.TimeDuration(), func() {
206 log.Fatalln("<run timed out>")
207 })
208 }
209 err = session.Run(events)
210 if err != nil {
211 log.Fatalln(err)
212 }
213 }