session.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package mcclient
  15. import (
  16. "context"
  17. "fmt"
  18. "io"
  19. "math/rand"
  20. "net/http"
  21. "regexp"
  22. "strings"
  23. "time"
  24. "yunion.io/x/jsonutils"
  25. "yunion.io/x/log"
  26. "yunion.io/x/pkg/appctx"
  27. "yunion.io/x/pkg/errors"
  28. "yunion.io/x/pkg/gotypes"
  29. "yunion.io/x/pkg/util/httputils"
  30. "yunion.io/x/pkg/utils"
  31. api "yunion.io/x/onecloud/pkg/apis/identity"
  32. "yunion.io/x/onecloud/pkg/cloudcommon/consts"
  33. )
  34. const (
  35. TASK_ID = "X-Task-Id"
  36. TASK_NOTIFY_URL = "X-Task-Notify-Url"
  37. AUTH_TOKEN = api.AUTH_TOKEN_HEADER // "X-Auth-Token"
  38. REGION_VERSION = "X-Region-Version"
  39. DEFAULT_API_VERSION = "v1"
  40. V2_API_VERSION = "v2"
  41. )
  42. type ClientSession struct {
  43. ctx context.Context
  44. client *Client
  45. region string
  46. zone string
  47. endpointType string
  48. token TokenCredential
  49. Header http.Header /// headers for this session
  50. notifyChannel chan string
  51. customizeServiceUrl map[string]string
  52. catalog IServiceCatalog
  53. }
  54. func populateHeader(self *http.Header, update http.Header) {
  55. for k, v := range update {
  56. for _, vv := range v {
  57. // self.Add(k, vv)
  58. self.Set(k, vv)
  59. }
  60. }
  61. }
  62. func GetTokenHeaders(userCred TokenCredential) http.Header {
  63. headers := http.Header{}
  64. headers.Set(AUTH_TOKEN, userCred.GetTokenString())
  65. headers.Set(REGION_VERSION, V2_API_VERSION)
  66. return headers
  67. }
  68. func SplitVersionedURL(url string) (string, string) {
  69. endidx := len(url) - 1
  70. for ; endidx >= 0 && url[endidx] == '/'; endidx-- {
  71. }
  72. lastslash := strings.LastIndexByte(url[0:endidx+1], '/')
  73. if lastslash >= 0 {
  74. if strings.EqualFold(url[lastslash+1:endidx+1], "latest") {
  75. return url[0:lastslash], ""
  76. }
  77. match, err := regexp.MatchString(`^v\d+\.?\d*`, url[lastslash+1:endidx+1])
  78. if err == nil && match {
  79. return url[0:lastslash], url[lastslash+1 : endidx+1]
  80. }
  81. }
  82. return url[0 : endidx+1], ""
  83. }
  84. /* func stripURLVersion(url string) string {
  85. base, _ := SplitVersionedURL(url)
  86. log.Debugf("stripURLVersion %s => %s", url, base)
  87. return base
  88. }*/
  89. func (cliss *ClientSession) GetEndpointType() string {
  90. return cliss.endpointType
  91. }
  92. func (cliss *ClientSession) GetClient() *Client {
  93. return cliss.client
  94. }
  95. func (cliss *ClientSession) SetZone(zone string) {
  96. cliss.zone = zone
  97. }
  98. func getApiVersionByServiceType(serviceType string) string {
  99. switch serviceType {
  100. case "compute":
  101. return "v2"
  102. }
  103. return ""
  104. }
  105. func (cliss *ClientSession) GetServiceName(service string) string {
  106. apiVersion := getApiVersionByServiceType(service)
  107. if len(apiVersion) > 0 && apiVersion != DEFAULT_API_VERSION {
  108. service = fmt.Sprintf("%s_%s", service, apiVersion)
  109. }
  110. return service
  111. }
  112. func (cliss *ClientSession) GetServiceURL(service, endpointType string, method httputils.THttpMethod) (string, error) {
  113. return cliss.GetServiceVersionURL(service, endpointType, method)
  114. }
  115. func (cliss *ClientSession) SetServiceCatalog(catalog IServiceCatalog) {
  116. cliss.catalog = catalog
  117. }
  118. func (cliss *ClientSession) GetServiceCatalog() IServiceCatalog {
  119. if cliss.catalog != nil {
  120. return cliss.catalog
  121. }
  122. return cliss.client.GetServiceCatalog()
  123. }
  124. func (cliss *ClientSession) GetServiceVersionURL(service, endpointType string, method httputils.THttpMethod) (string, error) {
  125. urls, err := cliss.GetServiceVersionURLs(service, endpointType, method)
  126. if err != nil {
  127. return "", errors.Wrap(err, "GetServiceVersionURLs")
  128. }
  129. return urls[rand.Intn(len(urls))], nil
  130. }
  131. func (cliss *ClientSession) GetServiceURLs(service, endpointType string, method httputils.THttpMethod) ([]string, error) {
  132. return cliss.GetServiceVersionURLs(service, endpointType, method)
  133. }
  134. func (cliss *ClientSession) GetServiceVersionURLs(service, endpointType string, method httputils.THttpMethod) ([]string, error) {
  135. return cliss.GetServiceVersionURLsByMethod(service, endpointType, method)
  136. }
  137. func (cliss *ClientSession) GetServiceVersionURLsByMethod(service, endpointType string, method httputils.THttpMethod) ([]string, error) {
  138. if len(cliss.endpointType) > 0 {
  139. // session specific endpoint type should override the input endpointType, which is supplied by manager
  140. endpointType = cliss.endpointType
  141. }
  142. service = cliss.GetServiceName(service)
  143. if endpointType == api.EndpointInterfaceApigateway {
  144. return cliss.getApigatewayServiceURLs(service, cliss.region, cliss.zone)
  145. } else {
  146. if (endpointType == "" || endpointType == api.EndpointInterfaceInternal) && (method == httputils.GET || method == httputils.HEAD) {
  147. urls, _ := cliss.getServiceVersionURLs(service, cliss.region, cliss.zone, api.EndpointInterfaceSlave)
  148. if len(urls) > 0 {
  149. return urls, nil
  150. }
  151. }
  152. return cliss.getServiceVersionURLs(service, cliss.region, cliss.zone, endpointType)
  153. }
  154. }
  155. func (cliss *ClientSession) getApigatewayServiceURLs(service, region, zone string) ([]string, error) {
  156. urls, err := cliss.getServiceVersionURLs(service, region, zone, api.EndpointInterfaceInternal)
  157. if err != nil {
  158. return nil, errors.Wrap(err, "getServiceVersionURLs")
  159. }
  160. // replace URLs with authUrl prefix
  161. // find the common prefix
  162. prefix := cliss.client.authUrl
  163. lastSlashPos := strings.LastIndex(prefix, "/api/s/identity")
  164. if lastSlashPos <= 0 {
  165. return nil, errors.Wrapf(errors.ErrInvalidFormat, "invalue auth_url %s, should be url of apigateway endpoint, e.g. https://<apigateway-host>/api/s/identity/v3", prefix)
  166. }
  167. prefix = httputils.JoinPath(prefix[:lastSlashPos], "api/s", service)
  168. if len(region) > 0 {
  169. prefix = httputils.JoinPath(prefix, "r", region)
  170. if len(zone) > 0 {
  171. prefix = httputils.JoinPath(prefix, "z", zone)
  172. }
  173. }
  174. rets := make([]string, len(urls))
  175. for i, url := range urls {
  176. if len(url) < 9 {
  177. // len("https://") == 8
  178. log.Errorf("invalid url %s: shorter than 9 bytes", url)
  179. continue
  180. }
  181. slashPos := strings.IndexByte(url[9:], '/')
  182. if slashPos > 0 {
  183. url = url[9+slashPos:]
  184. rets[i] = httputils.JoinPath(prefix, url)
  185. } else {
  186. rets[i] = prefix
  187. }
  188. }
  189. return rets, nil
  190. }
  191. func (cliss *ClientSession) getServiceVersionURLs(service, region, zone, endpointType string) ([]string, error) {
  192. catalog := cliss.GetServiceCatalog()
  193. if gotypes.IsNil(catalog) {
  194. return []string{cliss.client.authUrl}, nil
  195. }
  196. urls, err := catalog.getServiceURLs(service, region, zone, endpointType)
  197. // HACK! in case of fail to get keystone url or schema of keystone changed, always trust authUrl
  198. if service == api.SERVICE_TYPE && (err != nil || len(urls) == 0 || (len(cliss.client.authUrl) != 0 && cliss.client.authUrl[:5] != urls[0][:5])) {
  199. var msg string
  200. if err != nil {
  201. msg = fmt.Sprintf("fail to retrieve keystone urls: %s", err)
  202. } else if len(urls) == 0 {
  203. msg = "empty keystone url"
  204. } else {
  205. msg = fmt.Sprintf("Schema of keystone authUrl and endpoint mismatch: %s!=%s", cliss.client.authUrl, urls)
  206. }
  207. log.Warningln(msg)
  208. return []string{cliss.client.authUrl}, nil
  209. }
  210. if err != nil {
  211. return nil, errors.Wrap(err, "catalog.GetServiceURLs")
  212. }
  213. return urls, err
  214. }
  215. func (cliss *ClientSession) GetBaseUrl(service, endpointType string, method httputils.THttpMethod) (string, error) {
  216. if len(service) > 0 {
  217. if strings.HasPrefix(service, "http://") || strings.HasPrefix(service, "https://") {
  218. return service, nil
  219. } else if url, ok := cliss.customizeServiceUrl[service]; ok {
  220. return url, nil
  221. } else {
  222. return cliss.GetServiceVersionURL(service, endpointType, method)
  223. }
  224. } else {
  225. return "", fmt.Errorf("Empty service type or baseURL")
  226. }
  227. }
  228. func (cliss *ClientSession) RawBaseUrlRequest(
  229. service, endpointType string,
  230. method httputils.THttpMethod, url string,
  231. headers http.Header, body io.Reader,
  232. baseurlFactory func(string) string,
  233. ) (*http.Response, error) {
  234. baseurl, err := cliss.GetBaseUrl(service, endpointType, method)
  235. if err != nil {
  236. return nil, err
  237. }
  238. if baseurlFactory != nil {
  239. baseurl = baseurlFactory(baseurl)
  240. }
  241. tmpHeader := http.Header{}
  242. if headers != nil {
  243. populateHeader(&tmpHeader, headers)
  244. }
  245. populateHeader(&tmpHeader, cliss.Header)
  246. appctx.SetHTTPLangHeader(cliss.ctx, tmpHeader)
  247. ctx := cliss.ctx
  248. if cliss.ctx == nil {
  249. ctx = context.Background()
  250. }
  251. return cliss.client.rawRequest(ctx, baseurl,
  252. cliss.token.GetTokenString(),
  253. method, url, tmpHeader, body)
  254. }
  255. func (cliss *ClientSession) RawVersionRequest(
  256. service, endpointType string, method httputils.THttpMethod, url string,
  257. headers http.Header, body io.Reader,
  258. ) (*http.Response, error) {
  259. return cliss.RawBaseUrlRequest(service, endpointType, method, url, headers, body, nil)
  260. }
  261. func (cliss *ClientSession) RawRequest(service, endpointType string, method httputils.THttpMethod, url string, headers http.Header, body io.Reader) (*http.Response, error) {
  262. return cliss.RawVersionRequest(service, endpointType, method, url, headers, body)
  263. }
  264. func (cliss *ClientSession) JSONVersionRequest(
  265. service, endpointType string, method httputils.THttpMethod, url string,
  266. headers http.Header, body jsonutils.JSONObject,
  267. ) (http.Header, jsonutils.JSONObject, error) {
  268. baseUrl, err := cliss.GetBaseUrl(service, endpointType, method)
  269. if err != nil {
  270. return headers, nil, err
  271. }
  272. tmpHeader := http.Header{}
  273. if headers != nil {
  274. populateHeader(&tmpHeader, headers)
  275. }
  276. populateHeader(&tmpHeader, cliss.Header)
  277. appctx.SetHTTPLangHeader(cliss.ctx, tmpHeader)
  278. ctx := cliss.ctx
  279. if cliss.ctx == nil {
  280. ctx = context.Background()
  281. }
  282. return cliss.client.jsonRequest(ctx, baseUrl,
  283. cliss.token.GetTokenString(),
  284. method, url, tmpHeader, body)
  285. }
  286. func (cliss *ClientSession) JSONRequest(service, endpointType string, method httputils.THttpMethod, url string, headers http.Header, body jsonutils.JSONObject) (http.Header, jsonutils.JSONObject, error) {
  287. return cliss.JSONVersionRequest(service, endpointType, method, url, headers, body)
  288. }
  289. func (cliss *ClientSession) ParseJSONResponse(reqBody string, resp *http.Response, err error) (http.Header, jsonutils.JSONObject, error) {
  290. return httputils.ParseJSONResponse(reqBody, resp, err, cliss.client.debug)
  291. }
  292. func (cliss *ClientSession) HasSystemAdminPrivilege() bool {
  293. return cliss.token.HasSystemAdminPrivilege()
  294. }
  295. func (cliss *ClientSession) GetRegion() string {
  296. return cliss.region
  297. }
  298. func (cliss *ClientSession) GetUserId() string {
  299. return cliss.token.GetUserId()
  300. }
  301. func (cliss *ClientSession) GetTenantId() string {
  302. return cliss.token.GetTenantId()
  303. }
  304. func (cliss *ClientSession) GetTenantName() string {
  305. return cliss.token.GetTenantName()
  306. }
  307. func (cliss *ClientSession) GetProjectId() string {
  308. return cliss.GetTenantId()
  309. }
  310. func (cliss *ClientSession) GetProjectName() string {
  311. return cliss.GetTenantName()
  312. }
  313. func (cliss *ClientSession) GetProjectDomain() string {
  314. return cliss.token.GetProjectDomain()
  315. }
  316. func (cliss *ClientSession) GetProjectDomainId() string {
  317. return cliss.token.GetProjectDomainId()
  318. }
  319. func (cliss *ClientSession) GetDomainId() string {
  320. return cliss.token.GetDomainId()
  321. }
  322. func (cliss *ClientSession) GetDomainName() string {
  323. return cliss.token.GetDomainName()
  324. }
  325. func (cliss *ClientSession) SetTaskNotifyUrl(url string) {
  326. cliss.Header.Add(TASK_NOTIFY_URL, url)
  327. }
  328. func (cliss *ClientSession) RemoveTaskNotifyUrl() {
  329. cliss.Header.Del(TASK_NOTIFY_URL)
  330. }
  331. func (cliss *ClientSession) SetServiceUrl(service, url string) {
  332. cliss.customizeServiceUrl[service] = url
  333. }
  334. func (cliss *ClientSession) WithTaskCallback(taskId string, req func() error) error {
  335. baseUrl, err := cliss.GetBaseUrl(consts.GetServiceType(), api.EndpointInterfacePublic, httputils.POST)
  336. if err != nil {
  337. log.Errorf("GetServiceURLs error: %s", err)
  338. return errors.Wrap(err, "GetServiceURLs")
  339. }
  340. if len(baseUrl) == 0 {
  341. return errors.Wrap(errors.ErrInvalidFormat, "empty service url")
  342. }
  343. taskUrl := joinUrl(baseUrl, fmt.Sprintf("/tasks/%s", taskId))
  344. log.Infof("SetTaskNotifyUrl: %s service: %s", taskUrl, consts.GetServiceType())
  345. cliss.SetTaskNotifyUrl(taskUrl)
  346. defer cliss.RemoveTaskNotifyUrl()
  347. {
  348. err := req()
  349. if err != nil {
  350. return errors.Wrap(err, "Request")
  351. }
  352. }
  353. return nil
  354. }
  355. func (cliss *ClientSession) PrepareTask() {
  356. // start a random htttp server
  357. cliss.notifyChannel = make(chan string)
  358. s1 := rand.NewSource(time.Now().UnixNano())
  359. r1 := rand.New(s1)
  360. port := 55000 + r1.Intn(1000)
  361. ip := utils.GetOutboundIP()
  362. addr := fmt.Sprintf("%s:%d", ip.String(), port)
  363. url := fmt.Sprintf("http://%s", addr)
  364. cliss.SetTaskNotifyUrl(url)
  365. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  366. io.WriteString(w, "ok")
  367. body, err := io.ReadAll(r.Body)
  368. var msg string
  369. if err != nil {
  370. msg = fmt.Sprintf("Read request data error: %s", err)
  371. } else {
  372. msg = string(body)
  373. }
  374. cliss.notifyChannel <- msg
  375. })
  376. go func() {
  377. fmt.Println("List on address: ", url)
  378. if err := http.ListenAndServe(addr, nil); err != nil {
  379. fmt.Printf("Task notify server error: %s\n", err)
  380. }
  381. }()
  382. }
  383. func (cliss *ClientSession) WaitTaskNotify() {
  384. if cliss.notifyChannel != nil {
  385. msg := <-cliss.notifyChannel
  386. fmt.Println("---------------Task complete -------------")
  387. fmt.Println(msg)
  388. }
  389. }
  390. /*func (cliss *ClientSession) SetApiVersion(version string) {
  391. cliss.defaultApiVersion = version
  392. }
  393. func (cliss *ClientSession) GetApiVersion() string {
  394. apiVersion := cliss.getApiVersion("")
  395. if len(apiVersion) == 0 {
  396. return DEFAULT_API_VERSION
  397. }
  398. return apiVersion
  399. }*/
  400. func (cliss *ClientSession) ToJson() jsonutils.JSONObject {
  401. params := jsonutils.NewDict()
  402. simpleToken := SimplifyToken(cliss.token)
  403. tokenJson := jsonutils.Marshal(simpleToken)
  404. params.Update(tokenJson)
  405. // params.Add(jsonutils.NewString(cliss.GetApiVersion()), "api_version")
  406. if len(cliss.endpointType) > 0 {
  407. params.Add(jsonutils.NewString(cliss.endpointType), "endpoint_type")
  408. }
  409. if len(cliss.region) > 0 {
  410. params.Add(jsonutils.NewString(cliss.region), "region")
  411. }
  412. if len(cliss.zone) > 0 {
  413. params.Add(jsonutils.NewString(cliss.zone), "zone")
  414. }
  415. if tokenV3, ok := cliss.token.(*TokenCredentialV3); ok {
  416. params.Add(jsonutils.NewStringArray(tokenV3.Token.Policies.Project), "project_policies")
  417. params.Add(jsonutils.NewStringArray(tokenV3.Token.Policies.Domain), "domain_policies")
  418. params.Add(jsonutils.NewStringArray(tokenV3.Token.Policies.System), "system_policies")
  419. }
  420. return params
  421. }
  422. func (cliss *ClientSession) GetToken() TokenCredential {
  423. return cliss.token
  424. }
  425. func (cliss *ClientSession) GetContext() context.Context {
  426. if cliss.ctx == nil {
  427. return context.Background()
  428. }
  429. return cliss.ctx
  430. }
  431. func (cliss *ClientSession) GetCommonEtcdEndpoint() (*api.EndpointDetails, error) {
  432. return cliss.GetClient().GetCommonEtcdEndpoint(cliss.GetToken(), cliss.region, cliss.endpointType)
  433. }