harbor/service/utils/cache.go

73 lines
1.8 KiB
Go
Raw Normal View History

2016-02-01 12:59:10 +01:00
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2016-02-26 11:54:14 +01:00
2016-02-01 12:59:10 +01:00
package utils
import (
"encoding/json"
"time"
"github.com/vmware/harbor/models"
2016-03-25 02:31:50 +01:00
"github.com/vmware/harbor/utils/log"
2016-02-01 12:59:10 +01:00
"github.com/astaxie/beego/cache"
)
2016-02-26 11:35:55 +01:00
// Cache is the global cache in system.
2016-02-01 12:59:10 +01:00
var Cache cache.Cache
2016-02-26 11:35:55 +01:00
const catalogKey string = "catalog"
2016-02-01 12:59:10 +01:00
func init() {
var err error
Cache, err = cache.NewCache("memory", `{"interval":720}`)
if err != nil {
2016-03-26 17:18:11 +01:00
log.Errorf("Failed to initialize cache, error:%v", err)
2016-02-01 12:59:10 +01:00
}
}
2016-02-26 11:35:55 +01:00
// RefreshCatalogCache calls registry's API to get repository list and write it to cache.
2016-02-01 12:59:10 +01:00
func RefreshCatalogCache() error {
result, err := RegistryAPIGet(BuildRegistryURL("_catalog"), "")
2016-02-01 12:59:10 +01:00
if err != nil {
return err
}
repoResp := models.Repo{}
err = json.Unmarshal(result, &repoResp)
if err != nil {
return err
}
2016-02-26 11:35:55 +01:00
Cache.Put(catalogKey, repoResp.Repositories, 600*time.Second)
2016-02-01 12:59:10 +01:00
return nil
}
2016-02-26 11:35:55 +01:00
// GetRepoFromCache get repository list from cache, it refreshes the cache if it's empty.
2016-02-01 12:59:10 +01:00
func GetRepoFromCache() ([]string, error) {
2016-02-26 11:35:55 +01:00
result := Cache.Get(catalogKey)
2016-02-01 12:59:10 +01:00
if result == nil {
err := RefreshCatalogCache()
if err != nil {
return nil, err
}
2016-02-26 11:35:55 +01:00
cached := Cache.Get(catalogKey)
2016-02-01 12:59:10 +01:00
if cached != nil {
return cached.([]string), nil
}
return nil, nil
}
return result.([]string), nil
}