Skip to content

Commit

Permalink
Add AuthZ to Agents, Ratings and Schedules
Browse files Browse the repository at this point in the history
commit-id:aa055770
  • Loading branch information
tylerwowen committed May 15, 2024
1 parent 3dead2a commit 088dea6
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 69 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2016 Pinterest, Inc.
* Copyright (c) 2016-2024 Pinterest, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,32 +16,31 @@
package com.pinterest.teletraan.resource;

import com.pinterest.deployservice.bean.AgentBean;
import com.pinterest.deployservice.bean.TeletraanPrincipalRole;
import com.pinterest.deployservice.dao.AgentDAO;
import com.pinterest.teletraan.TeletraanServiceContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pinterest.teletraan.universal.security.ResourceAuthZInfo;
import com.pinterest.teletraan.universal.security.bean.AuthZResource;
import io.swagger.annotations.*;

import java.util.Collection;
import java.util.List;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;

import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@PermitAll
@Path("/v1/agents")
@Api(tags = "Agents")
@SwaggerDefinition(
tags = {
@Tag(name = "Agents", description = "Deploy agent information APIs"),
}
)
@Tag(name = "Agents", description = "Deploy agent information APIs"),
})
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Agents {
Expand All @@ -56,10 +55,12 @@ public Agents(@Context TeletraanServiceContext context) {
@ApiOperation(
value = "Get Deploy Agent Host Info",
notes = "Returns a list of all the deploy agent objects running on the specified host",
response = AgentBean.class, responseContainer = "List")
response = AgentBean.class,
responseContainer = "List")
@Path("/{hostName : [a-zA-Z0-9\\-_]+}")
public List<AgentBean> get(
@ApiParam(value = "Host name", required = true)@PathParam("hostName") String hostName) throws Exception {
@ApiParam(value = "Host name", required = true) @PathParam("hostName") String hostName)
throws Exception {
return agentDAO.getByHost(hostName);
}

Expand All @@ -71,18 +72,23 @@ public Collection<AgentBean> getById(@PathParam("hostId") String hostId) throws

@PUT
@Path("/id/{hostId : [a-zA-Z0-9\\-_]+}")
public void updateById(@Context SecurityContext sc,
@PathParam("hostId") String hostId,
@Valid AgentBean agentBean) throws Exception {
@RolesAllowed(TeletraanPrincipalRole.Names.EXECUTE)
@ResourceAuthZInfo(type = AuthZResource.Type.HOST, idLocation = ResourceAuthZInfo.Location.PATH)
public void updateById(
@Context SecurityContext sc,
@PathParam("hostId") String hostId,
@Valid AgentBean agentBean)
throws Exception {
String operator = sc.getUserPrincipal().getName();
agentDAO.updateAgentById(hostId, agentBean);
LOG.info("Successfully update agents {} by {}: {}", hostId, operator, agentBean.toString());
LOG.info("Successfully update agents {} by {}: {}", hostId, operator, agentBean);
}

@GET
@Path("/env/{envId : [a-zA-Z0-9\\-_]+}/total")
public long getCountByEnvName(
@ApiParam(value = "Env Id", required = true)@PathParam("envId") String envId) throws Exception {
@ApiParam(value = "Env Id", required = true) @PathParam("envId") String envId)
throws Exception {
return agentDAO.countAgentByEnv(envId);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2016 Pinterest, Inc.
* Copyright (c) 2016-2024 Pinterest, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -15,44 +15,50 @@
*/
package com.pinterest.teletraan.resource;

import com.google.common.base.Optional;
import com.pinterest.deployservice.bean.RatingBean;
import com.pinterest.deployservice.bean.TeletraanPrincipalRole;
import com.pinterest.deployservice.handler.RatingsHandler;
import com.pinterest.teletraan.TeletraanServiceContext;

import com.pinterest.teletraan.universal.security.ResourceAuthZInfo;
import com.pinterest.teletraan.universal.security.bean.AuthZResource;
import io.swagger.annotations.Api;

import java.net.URI;
import java.util.List;
import java.util.Optional;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.net.URI;
import java.util.List;

@PermitAll
@Path("/v1/ratings")
@Api(tags = "Ratings")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Ratings {
private final static int DEFAULT_INDEX = 1;
private final static int DEFAULT_SIZE = 30;
private static final int DEFAULT_INDEX = 1;
private static final int DEFAULT_SIZE = 30;
private RatingsHandler ratingsHandler;

public Ratings(@Context TeletraanServiceContext context) {
ratingsHandler = new RatingsHandler(context);
}

@GET
public List<RatingBean> getAll(@QueryParam("pageIndex") Optional<Integer> pageIndex,
@QueryParam("pageSize") Optional<Integer> pageSize) throws Exception {
return ratingsHandler.getRatingDAO().getRatingsInfos(pageIndex.or(DEFAULT_INDEX), pageSize.or(DEFAULT_SIZE));
public List<RatingBean> getAll(
@QueryParam("pageIndex") Optional<Integer> pageIndex,
@QueryParam("pageSize") Optional<Integer> pageSize)
throws Exception {
return ratingsHandler
.getRatingDAO()
.getRatingsInfos(pageIndex.orElse(DEFAULT_INDEX), pageSize.orElse(DEFAULT_SIZE));
}

@POST
public Response create(@Valid RatingBean bean,
@Context SecurityContext sc,
@Context UriInfo uriInfo) throws Exception {
public Response create(
@Valid RatingBean bean, @Context SecurityContext sc, @Context UriInfo uriInfo)
throws Exception {
bean.setAuthor(sc.getUserPrincipal().getName());
bean.setTimestamp(System.currentTimeMillis());
String id = ratingsHandler.createRating(bean);
Expand All @@ -64,12 +70,15 @@ public Response create(@Valid RatingBean bean,

@GET
@Path("/{userName : [a-zA-Z0-9\\-_.]+}/is_eligible")
public Boolean checkUserFeedbackStatus(@PathParam("userName") String userName) throws Exception {
public Boolean checkUserFeedbackStatus(@PathParam("userName") String userName)
throws Exception {
return ratingsHandler.checkUserFeebackStatus(userName);
}

@DELETE
@Path("/{id : [a-zA-Z0-9\\-_]+}")
@RolesAllowed(TeletraanPrincipalRole.Names.DELETE)
@ResourceAuthZInfo(type = AuthZResource.Type.SYSTEM)
public void delete(@PathParam("id") String id, @Context SecurityContext sc) throws Exception {
ratingsHandler.getRatingDAO().delete(id);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*sche
* Copyright 2016 Pinterest, Inc.
/**
* Copyright (c) 2016-2024 Pinterest, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -15,27 +15,26 @@
*/
package com.pinterest.teletraan.resource;

import com.pinterest.deployservice.bean.ScheduleState;
import com.pinterest.deployservice.bean.EnvironBean;
import com.pinterest.deployservice.bean.ScheduleBean;
import com.pinterest.deployservice.dao.ScheduleDAO;
import com.pinterest.deployservice.bean.ScheduleState;
import com.pinterest.deployservice.bean.TeletraanPrincipalRole;
import com.pinterest.deployservice.common.CommonUtils;
import com.pinterest.deployservice.dao.EnvironDAO;

import com.pinterest.deployservice.dao.ScheduleDAO;
import com.pinterest.teletraan.TeletraanServiceContext;

import com.pinterest.teletraan.universal.security.ResourceAuthZInfo;
import com.pinterest.teletraan.universal.security.bean.AuthZResource;
import io.swagger.annotations.Api;

import com.pinterest.deployservice.common.CommonUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@PermitAll
@Path("/v1/schedules")
Expand All @@ -47,36 +46,39 @@ public class Schedules {
private ScheduleDAO scheduleDAO;
private EnvironDAO environDAO;


public Schedules(@Context TeletraanServiceContext context) {
scheduleDAO = context.getScheduleDAO();
environDAO = context.getEnvironDAO();
}

@GET
@Path("/{envName : [a-zA-Z0-9\\-_]+}/{stageName : [a-zA-Z0-9\\-_]+}/{scheduleId : [a-zA-Z0-9\\-_]+}")
@Path(
"/{envName : [a-zA-Z0-9\\-_]+}/{stageName : [a-zA-Z0-9\\-_]+}/{scheduleId : [a-zA-Z0-9\\-_]+}")
public ScheduleBean getSchedule(
@Context SecurityContext sc,
@PathParam("envName") String envName,
@PathParam("stageName") String stageName,
@PathParam("scheduleId") String scheduleId) throws Exception {

String operator = sc.getUserPrincipal().getName();

@PathParam("scheduleId") String scheduleId)
throws Exception {
ScheduleBean scheduleBean = scheduleDAO.getById(scheduleId);
if (scheduleBean!=null) {
LOG.info(scheduleBean.toString());
if (scheduleBean != null) {
LOG.info("Schedule: {}", scheduleBean);
}
return scheduleBean;
}

@PUT
@Path("/{envName : [a-zA-Z0-9\\-_]+}/{stageName : [a-zA-Z0-9\\-_]+}/schedules")
@RolesAllowed(TeletraanPrincipalRole.Names.EXECUTE)
@ResourceAuthZInfo(
type = AuthZResource.Type.ENV_STAGE,
idLocation = ResourceAuthZInfo.Location.PATH)
public void updateSchedule(
@Context SecurityContext sc,
@PathParam("envName") String envName,
@PathParam("stageName") String stageName,
@Valid ScheduleBean bean) throws Exception {
@Valid ScheduleBean bean)
throws Exception {
String operator = sc.getUserPrincipal().getName();
EnvironBean envBean = environDAO.getByStage(envName, stageName);
String scheduleId = envBean.getSchedule_id();
Expand All @@ -89,54 +91,80 @@ public void updateSchedule(
scheduleBean.setCooldown_times(cooldownTimes);
scheduleBean.setHost_numbers(hostNumbers);
scheduleBean.setTotal_sessions(totalSessions);
LOG.info(scheduleBean.toString());
LOG.info("Schedule: {}", scheduleBean);
if (scheduleId == null) {
scheduleId = CommonUtils.getBase64UUID();
envBean.setSchedule_id(scheduleId);
environDAO.update(envName, stageName, envBean);
scheduleBean.setId(scheduleId);
scheduleDAO.insert(scheduleBean);
LOG.info(String.format("Successfully inserted one env %s (%s)'s schedule by %s: %s", envName, stageName, operator, scheduleBean.toString()));
LOG.info(
"Successfully inserted one env {} ({})'s schedule by {}: {}",
envName,
stageName,
operator,
scheduleBean);
} else {
scheduleBean.setId(scheduleId);
scheduleDAO.update(scheduleBean, scheduleId);
LOG.info(String.format("Successfully updated one env %s (%s)'s schedule by %s: %s", envName, stageName, operator, scheduleBean.toString()));
LOG.info(
"Successfully updated one env {} ({})'s schedule by {}: {}",
envName,
stageName,
operator,
scheduleBean);
}
} else if (scheduleId != null) { //there are no sessions, so delete the schedule
} else if (scheduleId != null) { // there are no sessions, so delete the schedule
scheduleDAO.delete(scheduleId);
environDAO.deleteSchedule(envName, stageName);
LOG.info(String.format("Successfully deleted env %s (%s)'s schedule by %s", envName, stageName, operator));
LOG.info(
"Successfully deleted env {} ({})'s schedule by {}",
envName,
stageName,
operator);
}
}

@PUT
@Path("/{envName : [a-zA-Z0-9\\-_]+}/{stageName : [a-zA-Z0-9\\-_]+}/override")
@RolesAllowed(TeletraanPrincipalRole.Names.EXECUTE)
@ResourceAuthZInfo(
type = AuthZResource.Type.ENV_STAGE,
idLocation = ResourceAuthZInfo.Location.PATH)
public void overrideSession(
@Context SecurityContext sc,
@PathParam("envName") String envName,
@PathParam("stageName") String stageName,
@QueryParam("sessionNumber") Integer sessionNumber) throws Exception {
String operator = sc.getUserPrincipal().getName();
@QueryParam("sessionNumber") Integer sessionNumber)
throws Exception {
EnvironBean envBean = environDAO.getByStage(envName, stageName);
String scheduleId = envBean.getSchedule_id();
if (scheduleId == null) {
LOG.info(String.format("Cannot override session, env %s has no schedule set", envName));
LOG.info("Cannot override session, env {} has no schedule set", envName);
return;
}
ScheduleBean scheduleBean = scheduleDAO.getById(scheduleId);
Integer currentSession = scheduleBean.getCurrent_session();
Integer totalSessions = scheduleBean.getTotal_sessions();
if (sessionNumber != currentSession) {
LOG.info(String.format("Overriding session %d is now invalid as deploy is already on session %d", sessionNumber, currentSession));
if (!sessionNumber.equals(currentSession)) {
LOG.info(
"Overriding session {} is now invalid as deploy is already on session {}",
sessionNumber,
currentSession);
return;
}
if (sessionNumber == totalSessions) {
if (sessionNumber.equals(totalSessions)) {
scheduleBean.setState(ScheduleState.FINAL);
LOG.info(String.format("Overrided session %d and currently working on the final deploy session", sessionNumber));
LOG.info(
"Overridden session {} and currently working on the final deploy session",
sessionNumber);
} else {
scheduleBean.setCurrent_session(sessionNumber+1);
scheduleBean.setCurrent_session(sessionNumber + 1);
scheduleBean.setState(ScheduleState.RUNNING);
LOG.info(String.format("Overrided session %d and currently working on session %d", sessionNumber, currentSession+1));
LOG.info(
"Overridden session {} and currently working on session {}",
sessionNumber,
currentSession + 1);
}
scheduleBean.setState_start_time(System.currentTimeMillis());
scheduleDAO.update(scheduleBean, scheduleId);
Expand Down

0 comments on commit 088dea6

Please sign in to comment.