本文整理汇总了Golang中github.com/vmware/harbor/src/common/utils/log.Errorf函数的典型用法代码示例。如果您正苦于以下问题:Golang Errorf函数的具体用法?Golang Errorf怎么用?Golang Errorf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Errorf函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Post
// Post ...
func (p *ProjectAPI) Post() {
p.userID = p.ValidateUser()
var req projectReq
p.DecodeJSONReq(&req)
public := req.Public
err := validateProjectReq(req)
if err != nil {
log.Errorf("Invalid project request, error: %v", err)
p.RenderError(http.StatusBadRequest, fmt.Sprintf("invalid request: %v", err))
return
}
projectName := req.ProjectName
exist, err := dao.ProjectExists(projectName)
if err != nil {
log.Errorf("Error happened checking project existence in db, error: %v, project name: %s", err, projectName)
}
if exist {
p.RenderError(http.StatusConflict, "")
return
}
project := models.Project{OwnerID: p.userID, Name: projectName, CreationTime: time.Now(), Public: public}
projectID, err := dao.AddProject(project)
if err != nil {
log.Errorf("Failed to add project, error: %v", err)
dup, _ := regexp.MatchString(dupProjectPattern, err.Error())
if dup {
p.RenderError(http.StatusConflict, "")
} else {
p.RenderError(http.StatusInternalServerError, "Failed to add project")
}
return
}
p.Redirect(http.StatusCreated, strconv.FormatInt(projectID, 10))
}
示例2: Get
// Get ...
func (ua *UserAPI) Get() {
if ua.userID == 0 { //list users
if !ua.IsAdmin {
log.Errorf("Current user, id: %d does not have admin role, can not list users", ua.currentUserID)
ua.RenderError(http.StatusForbidden, "User does not have admin role")
return
}
username := ua.GetString("username")
userQuery := models.User{}
if len(username) > 0 {
userQuery.Username = "%" + username + "%"
}
userList, err := dao.ListUsers(userQuery)
if err != nil {
log.Errorf("Failed to get data from database, error: %v", err)
ua.RenderError(http.StatusInternalServerError, "Failed to query from database")
return
}
ua.Data["json"] = userList
} else if ua.userID == ua.currentUserID || ua.IsAdmin {
userQuery := models.User{UserID: ua.userID}
u, err := dao.GetUser(userQuery)
if err != nil {
log.Errorf("Error occurred in GetUser, error: %v", err)
ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
ua.Data["json"] = u
} else {
log.Errorf("Current user, id: %d does not have admin role, can not view other user's detail", ua.currentUserID)
ua.RenderError(http.StatusForbidden, "User does not have admin role")
return
}
ua.ServeJSON()
}
示例3: ResetPassword
// ResetPassword handles request from the reset page and reset password
func (cc *CommonController) ResetPassword() {
resetUUID := cc.GetString("reset_uuid")
if resetUUID == "" {
cc.CustomAbort(http.StatusBadRequest, "Reset uuid is blank.")
}
queryUser := models.User{ResetUUID: resetUUID}
user, err := dao.GetUser(queryUser)
if err != nil {
log.Errorf("Error occurred in GetUser: %v", err)
cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if user == nil {
log.Error("User does not exist")
cc.CustomAbort(http.StatusBadRequest, "User does not exist")
}
password := cc.GetString("password")
if password != "" {
user.Password = password
err = dao.ResetUserPassword(*user)
if err != nil {
log.Errorf("Error occurred in ResetUserPassword: %v", err)
cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
} else {
cc.CustomAbort(http.StatusBadRequest, "password_is_required")
}
}
示例4: Get
// Get ...
func (t *TargetAPI) Get() {
id := t.GetIDFromURL()
target, err := dao.GetRepTarget(id)
if err != nil {
log.Errorf("failed to get target %d: %v", id, err)
t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
}
if target == nil {
t.CustomAbort(http.StatusNotFound, http.StatusText(http.StatusNotFound))
}
// The reason why the password is returned is that when user just wants to
// modify other fields of target he does not need to input the password again.
// The security issue can be fixed by enable https.
if len(target.Password) != 0 {
pwd, err := utils.ReversibleDecrypt(target.Password, t.secretKey)
if err != nil {
log.Errorf("failed to decrypt password: %v", err)
t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
}
target.Password = pwd
}
t.Data["json"] = target
t.ServeJSON()
}
示例5: listRoles
//sysadmin has all privileges to all projects
func listRoles(userID int, projectID int64) ([]models.Role, error) {
roles := make([]models.Role, 0, 1)
isSysAdmin, err := dao.IsAdminRole(userID)
if err != nil {
log.Errorf("failed to determine whether the user %d is system admin: %v", userID, err)
return roles, err
}
if isSysAdmin {
role, err := dao.GetRoleByID(models.PROJECTADMIN)
if err != nil {
log.Errorf("failed to get role %d: %v", models.PROJECTADMIN, err)
return roles, err
}
roles = append(roles, *role)
return roles, nil
}
rs, err := dao.GetUserProjectRoles(userID, projectID)
if err != nil {
log.Errorf("failed to get user %d 's roles for project %d: %v", userID, projectID, err)
return roles, err
}
roles = append(roles, rs...)
return roles, nil
}
示例6: Delete
// Delete : policies which are disabled and have no running jobs
// can be deleted
func (pa *RepPolicyAPI) Delete() {
id := pa.GetIDFromURL()
policy, err := dao.GetRepPolicy(id)
if err != nil {
log.Errorf("failed to get policy %d: %v", id, err)
pa.CustomAbort(http.StatusInternalServerError, "")
}
if policy == nil || policy.Deleted == 1 {
pa.CustomAbort(http.StatusNotFound, "")
}
if policy.Enabled == 1 {
pa.CustomAbort(http.StatusPreconditionFailed, "plicy is enabled, can not be deleted")
}
jobs, err := dao.GetRepJobByPolicy(id)
if err != nil {
log.Errorf("failed to get jobs of policy %d: %v", id, err)
pa.CustomAbort(http.StatusInternalServerError, "")
}
for _, job := range jobs {
if job.Status == models.JobRunning ||
job.Status == models.JobRetrying ||
job.Status == models.JobPending {
pa.CustomAbort(http.StatusPreconditionFailed, "policy has running/retrying/pending jobs, can not be deleted")
}
}
if err = dao.DeleteRepPolicy(id); err != nil {
log.Errorf("failed to delete policy %d: %v", id, err)
pa.CustomAbort(http.StatusInternalServerError, "")
}
}
示例7: List
// List ...
func (t *TargetAPI) List() {
name := t.GetString("name")
targets, err := dao.FilterRepTargets(name)
if err != nil {
log.Errorf("failed to filter targets %s: %v", name, err)
t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
}
for _, target := range targets {
if len(target.Password) == 0 {
continue
}
str, err := utils.ReversibleDecrypt(target.Password, t.secretKey)
if err != nil {
log.Errorf("failed to decrypt password: %v", err)
t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
}
target.Password = str
}
t.Data["json"] = targets
t.ServeJSON()
return
}
示例8: Delete
// Delete ...
func (t *TargetAPI) Delete() {
id := t.GetIDFromURL()
target, err := dao.GetRepTarget(id)
if err != nil {
log.Errorf("failed to get target %d: %v", id, err)
t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
}
if target == nil {
t.CustomAbort(http.StatusNotFound, http.StatusText(http.StatusNotFound))
}
policies, err := dao.GetRepPolicyByTarget(id)
if err != nil {
log.Errorf("failed to get policies according target %d: %v", id, err)
t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
}
if len(policies) > 0 {
t.CustomAbort(http.StatusBadRequest, "the target is used by policies, can not be deleted")
}
if err = dao.DeleteRepTarget(id); err != nil {
log.Errorf("failed to delete target %d: %v", id, err)
t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
}
}
示例9: Get
// Get ...
func (s *SearchAPI) Get() {
userID, _, ok := s.GetUserIDForRequest()
if !ok {
userID = dao.NonExistUserID
}
keyword := s.GetString("q")
isSysAdmin, err := dao.IsAdminRole(userID)
if err != nil {
log.Errorf("failed to check whether the user %d is system admin: %v", userID, err)
s.CustomAbort(http.StatusInternalServerError, "internal error")
}
var projects []models.Project
if isSysAdmin {
projects, err = dao.GetProjects("")
if err != nil {
log.Errorf("failed to get all projects: %v", err)
s.CustomAbort(http.StatusInternalServerError, "internal error")
}
} else {
projects, err = dao.SearchProjects(userID)
if err != nil {
log.Errorf("failed to get user %d 's relevant projects: %v", userID, err)
s.CustomAbort(http.StatusInternalServerError, "internal error")
}
}
projectSorter := &models.ProjectSorter{Projects: projects}
sort.Sort(projectSorter)
projectResult := []map[string]interface{}{}
for _, p := range projects {
match := true
if len(keyword) > 0 && !strings.Contains(p.Name, keyword) {
match = false
}
if match {
entry := make(map[string]interface{})
entry["id"] = p.ProjectID
entry["name"] = p.Name
entry["public"] = p.Public
projectResult = append(projectResult, entry)
}
}
repositories, err := cache.GetRepoFromCache()
if err != nil {
log.Errorf("failed to list repositories: %v", err)
s.CustomAbort(http.StatusInternalServerError, "")
}
sort.Strings(repositories)
repositoryResult := filterRepositories(repositories, projects, keyword)
result := &searchResult{Project: projectResult, Repository: repositoryResult}
s.Data["json"] = result
s.ServeJSON()
}
示例10: List
// List filters jobs according to the parameters
func (ra *RepJobAPI) List() {
policyID, err := ra.GetInt64("policy_id")
if err != nil || policyID <= 0 {
ra.CustomAbort(http.StatusBadRequest, "invalid policy_id")
}
policy, err := dao.GetRepPolicy(policyID)
if err != nil {
log.Errorf("failed to get policy %d: %v", policyID, err)
ra.CustomAbort(http.StatusInternalServerError, "")
}
if policy == nil {
ra.CustomAbort(http.StatusNotFound, fmt.Sprintf("policy %d not found", policyID))
}
repository := ra.GetString("repository")
status := ra.GetString("status")
var startTime *time.Time
startTimeStr := ra.GetString("start_time")
if len(startTimeStr) != 0 {
i, err := strconv.ParseInt(startTimeStr, 10, 64)
if err != nil {
ra.CustomAbort(http.StatusBadRequest, "invalid start_time")
}
t := time.Unix(i, 0)
startTime = &t
}
var endTime *time.Time
endTimeStr := ra.GetString("end_time")
if len(endTimeStr) != 0 {
i, err := strconv.ParseInt(endTimeStr, 10, 64)
if err != nil {
ra.CustomAbort(http.StatusBadRequest, "invalid end_time")
}
t := time.Unix(i, 0)
endTime = &t
}
page, pageSize := ra.GetPaginationParams()
jobs, total, err := dao.FilterRepJobs(policyID, repository, status,
startTime, endTime, pageSize, pageSize*(page-1))
if err != nil {
log.Errorf("failed to filter jobs according policy ID %d, repository %s, status %s, start time %v, end time %v: %v",
policyID, repository, status, startTime, endTime, err)
ra.CustomAbort(http.StatusInternalServerError, "")
}
ra.SetPaginationHeader(total, page, pageSize)
ra.Data["json"] = jobs
ra.ServeJSON()
}
示例11: Get
// Get ...
func (ra *RepositoryAPI) Get() {
projectID, err := ra.GetInt64("project_id")
if err != nil || projectID <= 0 {
ra.CustomAbort(http.StatusBadRequest, "invalid project_id")
}
page, pageSize := ra.GetPaginationParams()
project, err := dao.GetProjectByID(projectID)
if err != nil {
log.Errorf("failed to get project %d: %v", projectID, err)
ra.CustomAbort(http.StatusInternalServerError, "")
}
if project == nil {
ra.CustomAbort(http.StatusNotFound, fmt.Sprintf("project %d not found", projectID))
}
if project.Public == 0 {
var userID int
if svc_utils.VerifySecret(ra.Ctx.Request) {
userID = 1
} else {
userID = ra.ValidateUser()
}
if !checkProjectPermission(userID, projectID) {
ra.CustomAbort(http.StatusForbidden, "")
}
}
repositories, err := getReposByProject(project.Name, ra.GetString("q"))
if err != nil {
log.Errorf("failed to get repository: %v", err)
ra.CustomAbort(http.StatusInternalServerError, "")
}
total := int64(len(repositories))
if (page-1)*pageSize > total {
repositories = []string{}
} else {
repositories = repositories[(page-1)*pageSize:]
}
if page*pageSize <= total {
repositories = repositories[:pageSize]
}
ra.SetPaginationHeader(total, page, pageSize)
ra.Data["json"] = repositories
ra.ServeJSON()
}
示例12: GetTags
// GetTags handles GET /api/repositories/tags
func (ra *RepositoryAPI) GetTags() {
repoName := ra.GetString("repo_name")
if len(repoName) == 0 {
ra.CustomAbort(http.StatusBadRequest, "repo_name is nil")
}
projectName, _ := utils.ParseRepository(repoName)
project, err := dao.GetProjectByName(projectName)
if err != nil {
log.Errorf("failed to get project %s: %v", projectName, err)
ra.CustomAbort(http.StatusInternalServerError, "")
}
if project == nil {
ra.CustomAbort(http.StatusNotFound, fmt.Sprintf("project %s not found", projectName))
}
if project.Public == 0 {
userID := ra.ValidateUser()
if !checkProjectPermission(userID, project.ProjectID) {
ra.CustomAbort(http.StatusForbidden, "")
}
}
rc, err := ra.initRepositoryClient(repoName)
if err != nil {
log.Errorf("error occurred while initializing repository client for %s: %v", repoName, err)
ra.CustomAbort(http.StatusInternalServerError, "internal error")
}
tags := []string{}
ts, err := rc.ListTag()
if err != nil {
regErr, ok := err.(*registry_error.Error)
if !ok {
log.Errorf("error occurred while listing tags of %s: %v", repoName, err)
ra.CustomAbort(http.StatusInternalServerError, "internal error")
}
// TODO remove the logic if the bug of registry is fixed
// It's a workaround for a bug of registry: when listing tags of
// a repository which is being pushed, a "NAME_UNKNOWN" error will
// been returned, while the catalog API can list this repository.
if regErr.StatusCode != http.StatusNotFound {
ra.CustomAbort(regErr.StatusCode, regErr.Detail)
}
}
tags = append(tags, ts...)
sort.Strings(tags)
ra.Data["json"] = tags
ra.ServeJSON()
}
示例13: Prepare
// Prepare validates the URL and parms
func (ua *UserAPI) Prepare() {
authMode := strings.ToLower(os.Getenv("AUTH_MODE"))
if authMode == "" {
authMode = "db_auth"
}
ua.AuthMode = authMode
selfRegistration := strings.ToLower(os.Getenv("SELF_REGISTRATION"))
if selfRegistration == "on" {
ua.SelfRegistration = true
}
if ua.Ctx.Input.IsPost() {
sessionUserID := ua.GetSession("userId")
_, _, ok := ua.Ctx.Request.BasicAuth()
if sessionUserID == nil && !ok {
return
}
}
ua.currentUserID = ua.ValidateUser()
id := ua.Ctx.Input.Param(":id")
if id == "current" {
ua.userID = ua.currentUserID
} else if len(id) > 0 {
var err error
ua.userID, err = strconv.Atoi(id)
if err != nil {
log.Errorf("Invalid user id, error: %v", err)
ua.CustomAbort(http.StatusBadRequest, "Invalid user Id")
}
userQuery := models.User{UserID: ua.userID}
u, err := dao.GetUser(userQuery)
if err != nil {
log.Errorf("Error occurred in GetUser, error: %v", err)
ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if u == nil {
log.Errorf("User with Id: %d does not exist", ua.userID)
ua.CustomAbort(http.StatusNotFound, "")
}
}
var err error
ua.IsAdmin, err = dao.IsAdminRole(ua.currentUserID)
if err != nil {
log.Errorf("Error occurred in IsAdminRole:%v", err)
ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
}
示例14: FilterAccess
// FilterAccess modify the action list in access based on permission
func FilterAccess(username string, a *token.ResourceActions) {
if a.Type == "registry" && a.Name == "catalog" {
log.Infof("current access, type: %s, name:%s, actions:%v \n", a.Type, a.Name, a.Actions)
return
}
//clear action list to assign to new acess element after perm check.
a.Actions = []string{}
if a.Type == "repository" {
if strings.Contains(a.Name, "/") { //Only check the permission when the requested image has a namespace, i.e. project
projectName := a.Name[0:strings.LastIndex(a.Name, "/")]
var permission string
if len(username) > 0 {
isAdmin, err := dao.IsAdminRole(username)
if err != nil {
log.Errorf("Error occurred in IsAdminRole: %v", err)
}
if isAdmin {
exist, err := dao.ProjectExists(projectName)
if err != nil {
log.Errorf("Error occurred in CheckExistProject: %v", err)
return
}
if exist {
permission = "RWM"
} else {
permission = ""
log.Infof("project %s does not exist, set empty permission for admin\n", projectName)
}
} else {
permission, err = dao.GetPermission(username, projectName)
if err != nil {
log.Errorf("Error occurred in GetPermission: %v", err)
return
}
}
}
if strings.Contains(permission, "W") {
a.Actions = append(a.Actions, "push")
}
if strings.Contains(permission, "M") {
a.Actions = append(a.Actions, "*")
}
if strings.Contains(permission, "R") || dao.IsProjectPublic(projectName) {
a.Actions = append(a.Actions, "pull")
}
}
}
log.Infof("current access, type: %s, name:%s, actions:%v \n", a.Type, a.Name, a.Actions)
}
示例15: TestGetRepoJobToStop
func TestGetRepoJobToStop(t *testing.T) {
jobs := [...]models.RepJob{
models.RepJob{
Repository: "library/ubuntu",
PolicyID: policyID,
Operation: "transfer",
Status: models.JobRunning,
},
models.RepJob{
Repository: "library/ubuntu",
PolicyID: policyID,
Operation: "transfer",
Status: models.JobFinished,
},
models.RepJob{
Repository: "library/ubuntu",
PolicyID: policyID,
Operation: "transfer",
Status: models.JobCanceled,
},
}
var err error
var i int64
var ids []int64
for _, j := range jobs {
i, err = AddRepJob(j)
ids = append(ids, i)
if err != nil {
log.Errorf("Failed to add Job: %+v, error: %v", j, err)
return
}
}
res, err := GetRepJobToStop(policyID)
if err != nil {
log.Errorf("Failed to Get Jobs, error: %v", err)
return
}
//time.Sleep(15 * time.Second)
if len(res) != 1 {
log.Errorf("Expected length of stoppable jobs, expected:1, in fact: %d", len(res))
return
}
for _, id := range ids {
err = DeleteRepJob(id)
if err != nil {
log.Errorf("Failed to delete job, id: %d, error: %v", id, err)
return
}
}
}