Пример #1
0
def create(solEnvDetails):
    logger.debug("solutionEnvironment::create: %s", solEnvDetails)
    # Remove the id
    solEnvDetails.pop("id", None)
    # Does the solution environment exist?
    existing_sol_env = (db.session.query(SolutionEnvironment).filter(
        SolutionEnvironment.solutionId == solEnvDetails["solutionId"],
        SolutionEnvironment.environmentId == solEnvDetails["environmentId"],
    ).one_or_none())
    schema = SolutionEnvironmentSchema()

    # Does sol_env exist?
    if existing_sol_env is not None:
        logger.debug("solutionEnvironment::update: %s", existing_sol_env)
        existing_sol_env.isActive = solEnvDetails.get("isActive", True)
        existing_sol_env.lastUpdated = ModelTools.get_utc_timestamp()
        db.session.merge(existing_sol_env)
        db.session.commit()
        data = schema.dump(existing_sol_env)
        return data, 201
    else:
        logger.debug("solutionEnvironment::create: %s", solEnvDetails)
        sol_env_change = schema.load(solEnvDetails, session=db.session)
        sol_env_change.isActive = solEnvDetails.get("isActive", True)
        sol_env_change.lastUpdated = ModelTools.get_utc_timestamp()
        db.session.add(sol_env_change)
        db.session.commit()
        data = schema.dump(sol_env_change)
        return data, 201
Пример #2
0
def update(settingsDetails):
    """
    Updates an existing settings entry in the system settings.

    :param settingsDetails:     details to update
    :return:       updated settings
    """
    user = security.get_valid_user_from_token(dbsession=db.session)
    logger.debug(f"Logged in user {user}")
    if not (user and user.isLZAdmin):
        return abort(401, "JWT not valid or user is not a Landing Zone Admin")

    s: SystemSettings = (db.session.query(SystemSettings).filter(
        SystemSettings.userId == user.id).one_or_none())
    if s is not None:
        s.username = settingsDetails["username"]
        s.token = settingsDetails["token"]
        s.lastUpdated = ModelTools.get_utc_timestamp()

        db.session.merge(s)
        db.session.commit()

        resultSchema = SystemSettingsResultSchema()
        data = resultSchema.dump(s)

        return data, 200

    return abort(404, "System settings not found")
Пример #3
0
def lzenv_app_deployment(lzenv, dbs, sol, app_id, app):
    workspace_resource_key = "project-id-workspace"
    workspace_resource = (dbs.query(SolutionResource).filter(
        SolutionResource.solutionId == sol.id,
        SolutionResource.key == workspace_resource_key,
    ).one_or_none())
    if not workspace_resource:
        logger.error(
            "deployment_create: This application deployment %s is missing the workspaceProjectId, resourceKey: %s, skipping...",
            app_id,
            workspace_resource_key,
        )

    if workspace_resource:
        workspaceProjectId = workspace_resource.value
        resource_key = f"project-id-{lzenv.name.lower()}"

        solution_resource = (dbs.query(SolutionResource).filter(
            SolutionResource.solutionId == sol.id,
            SolutionResource.key == resource_key,
        ).one_or_none())

        if not solution_resource:
            logger.error(
                "deployment_create: This application deployment %s is missing the projectId, resourceKey: %s, skipping...",
                app_id,
                resource_key,
            )

        if solution_resource:
            projectId = solution_resource.value
            app_deployment = (dbs.query(ApplicationDeployment).filter(
                ApplicationDeployment.solutionId == sol.id,
                ApplicationDeployment.applicationId == app_id,
                ApplicationDeployment.lzEnvironmentId == lzenv.id,
            ).one_or_none())
        if not app_deployment:
            schema = ApplicationDeploymentSchema(many=False)
            app_deployment_dict = {}
            app_deployment_dict["applicationId"] = app_id
            app_deployment_dict["lastUpdated"] = ModelTools.get_utc_timestamp()
            app_deployment_dict["deploymentState"] = DeploymentStatus.PENDING
            app_deployment_dict["taskId"] = None
            app_deployment_dict["solutionId"] = app.solutionId
            app_deployment_dict["deploymentProjectId"] = projectId
            app_deployment_dict["lzEnvironmentId"] = lzenv.id
            app_deployment_dict["workspaceProjectId"] = workspaceProjectId

            app_deployment = schema.load(app_deployment_dict,
                                         session=db.session)
            dbs.add(app_deployment)
        else:
            # Allow re-deployment of a previously unsuccessful deployment
            if app_deployment.deploymentState != DeploymentStatus.SUCCESS:
                app_deployment.deploymentState = DeploymentStatus.PENDING
                app_deployment.taskId = None
Пример #4
0
    def serialize_pre_load(self, data, **kwargs):
        logger.debug("TeamSchem::pre_load::serialize_pre_load: %s", data)
        data["lastUpdated"] = ModelTools.get_utc_timestamp()
        if "isActive" not in data:
            data["isActive"] = True
        if data.get("accessRequestedById") == 0:
            data["accessRequestedById"] = None
        if data.get("cloudIdentityGroup") is None:
            data["cloudIdentityGroup"] = ""

        return data
Пример #5
0
def update(oid, teamDetails):
    """
    Updates an existing team in the team list

    :param id:    id of the team to update in the team list
    :param team:   team to update
    :return:       updated team.
    """
    app.logger.debug(pformat(teamDetails))
    if teamDetails.get("id") and teamDetails.get("id") != int(oid):
        abort(400, "Id mismatch in path and body")

    # Does the team exist in team list?
    existing_team = db.session.query(Team).filter(Team.id == oid).one_or_none()

    # Does team exist?

    if existing_team is not None:
        schema = TeamSchema()
        update_team = schema.load(teamDetails, session=db.session)
        update_team.name = teamDetails.get("name", existing_team.name)
        update_team.description = teamDetails.get("description",
                                                  existing_team.description)
        update_team.cloudIdentityGroup = teamDetails.get(
            "cloudIdentityGroup", existing_team.cloudIdentityGroup)
        update_team.businessUnitId = teamDetails.get(
            "businessUnitId", existing_team.businessUnitId)
        update_team.accessRequestedById = teamDetails.get(
            "accessRequestedById", existing_team.accessRequestedById)
        update_team.lastUpdated = ModelTools.get_utc_timestamp()
        update_team.isActive = teamDetails.get("isActive",
                                               existing_team.isActive)

        db.session.merge(update_team)
        try:
            db.session.commit()
        except exc.IntegrityError as err:
            db.session.rollback()
            app.logger.debug(str(err))
            if "Duplicate entry" in str(err):
                return abort(400, "Team already exists")
            else:
                return abort(400, "Unknown Integrity Error adding team")
        except Exception as err:
            db.session.rollback()
            app.logger.debug(str(err))
            return abort(400, "Unknown error adding team")

        # return the updted team in the response
        data = schema.dump(update_team)
        return data, 200

    # otherwise, nope, deployment doesn't exist, so that's an error
    abort(404, "Team not found")
Пример #6
0
 def serialize_pre_load(self, data, **kwargs):
     logger.debug("ApplicationSchema::pre_load::serialize_pre_load: %s", data)
     data["lastUpdated"] = ModelTools.get_utc_timestamp()
     if "isActive" not in data:
         data["isActive"] = True
     if "isFavourite" not in data:
         data["isFavourite"] = False
     if "resources" in data:
         data["resources"] = json.dumps(data["resources"])
     else:
         data["resources"] = "[]"
     return data
Пример #7
0
def deployment_update(oid, solutionDeploymentDetails):
    """
    Updates an existing solutions in the solutions list with the deployed status.

    :param key:    id of the solution
    :param solutionDetails:   solution details to update
    :return:       updated solution
    """
    logger.debug(solutionDeploymentDetails)

    # Does the solutions exist in solutions list?
    existing_solution = (db.session.query(Solution).filter(
        Solution.id == oid).one_or_none())

    # Does solutions exist?

    if existing_solution is not None:
        schema = SolutionSchema(many=False)
        update_solution = schema.load(solutionDeploymentDetails,
                                      session=db.session)
        update_solution.id = oid
        update_solution.lastUpdated = ModelTools.get_utc_timestamp()
        update_solution.deployed = solutionDeploymentDetails.get(
            "deployed", existing_solution.deployed)
        update_solution.deploymentState = solutionDeploymentDetails.get(
            "deploymentState", existing_solution.deploymentState)
        update_solution.statusId = solutionDeploymentDetails.get(
            "statusId", existing_solution.statusId)
        update_solution.statusCode = solutionDeploymentDetails.get(
            "statusCode", existing_solution.statusCode)
        update_solution.statusMessage = solutionDeploymentDetails.get(
            "statusMessage", existing_solution.statusMessage)
        update_solution.taskId = solutionDeploymentDetails.get(
            "taskId", existing_solution.taskId)
        update_solution.deploymentFolderId = solutionDeploymentDetails.get(
            "deploymentFolderId", existing_solution.deploymentFolderId)
        update_solution.isSandbox = solutionDeploymentDetails.get(
            "isSandbox", existing_solution.isSandbox)

        db.session.merge(update_solution)
        db.session.commit()

        # return the updted solutions in the response
        schema = SolutionDeploymentSchema(many=False)
        data = schema.dump(update_solution)
        return data, 200

    # otherwise, nope, deployment doesn't exist, so that's an error
    else:
        abort(404, f"Solution {oid} not found")
Пример #8
0
def update_activator_metadata_platforms(platforms, activator_metadata_id, dbsession):
    for platform in platforms:
        platform = (
            dbsession.query(ActivatorMetadataPlatform)
            .filter(
                ActivatorMetadataPlatform.activatorMetadataId == activator_metadata_id,
                ActivatorMetadataPlatform.platformId == platform.get("id"),
            )
            .one_or_none()
        )
        platform.lastUpdated = ModelTools.get_utc_timestamp()
        platform.isActive = True
        dbsession.add(platform)
        dbsession.flush()
Пример #9
0
def delete(oid, dbsession):
    logger.debug("delete: %s", oid)
    na = (dbsession.query(NotificationActivator).filter(
        NotificationActivator.notificationId == oid,
        NotificationActivator.isActive).one_or_none())
    if na:
        na.isActive = False
        na.lastUpdated = ModelTools.get_utc_timestamp()

    nt = (dbsession.query(NotificationTeam).filter(
        NotificationTeam.notificationId == oid,
        NotificationTeam.isActive).one_or_none())
    if nt:
        nt.isActive = False
        nt.lastUpdated = ModelTools.get_utc_timestamp()

    nad = (dbsession.query(NotificationApplicationDeployment).filter(
        NotificationApplicationDeployment.notificationId == oid,
        NotificationApplicationDeployment.isActive,
    ).one_or_none())
    if nt:
        nad.isActive = False
        nad.lastUpdated = ModelTools.get_utc_timestamp()

    nsd = (dbsession.query(NotificationSolutionDeployment).filter(
        NotificationSolutionDeployment.notificationId == oid,
        NotificationSolutionDeployment.isActive,
    ).one_or_none())
    if nt:
        nsd.isActive = False
        nsd.lastUpdated = ModelTools.get_utc_timestamp()

    n = (dbsession.query(Notification).filter(
        Notification.id == oid, Notification.isActive).one_or_none())
    if n:
        n.isActive = False
        n.lastUpdated = ModelTools.get_utc_timestamp()
Пример #10
0
def create_activator_metadata_platforms(dbs, act_metadata_yml,
                                        activator_metadata_id):
    schema = ActivatorMetadataPlatformSchema()
    platforms = act_metadata_yml["platforms"]

    for p in platforms:
        actPlatformDetails = {}
        actPlatformDetails["activatorMetadataId"] = activator_metadata_id
        actPlatformDetails["platformId"] = (dbs.query(Platform).filter(
            Platform.value == p).one_or_none()).id
        actPlatformDetails["lastUpdated"] = ModelTools.get_utc_timestamp()
        actPlatformDetails["isActive"] = True
        activator_metadata_platform = schema.load(actPlatformDetails,
                                                  session=dbs)
        dbs.add(activator_metadata_platform)
        dbs.flush()
Пример #11
0
def create_activator_metadata(dbs, act_metadata_yml, activator_id, url):
    schema = ActivatorMetadataSchema()
    actMetaDetails = {}
    actMetaDetails["activatorId"] = activator_id
    actMetaDetails["name"] = act_metadata_yml["name"]
    actMetaDetails["description"] = act_metadata_yml["description"]
    actMetaDetails["category"] = act_metadata_yml["category"]
    actMetaDetails["activatorLink"] = url
    actMetaDetails["typeId"] = (dbs.query(Type).filter(
        Type.value == act_metadata_yml["type"]).one_or_none()).id
    actMetaDetails["lastUpdated"] = ModelTools.get_utc_timestamp()
    actMetaDetails["latestVersion"] = act_metadata_yml["latestVersion"]
    activator_metadata = schema.load(actMetaDetails, session=dbs)
    dbs.add(activator_metadata)
    dbs.flush()
    return activator_metadata
Пример #12
0
def update_activator_metadata(activator_id, act_metadata, dbsession):
    actMetaDetails = (
        dbsession.query(ActivatorMetadata)
        .filter(ActivatorMetadata.activatorId == activator_id)
        .one_or_none()
    )
    if actMetaDetails:
        actMetaDetails.name = act_metadata.get("name")
        actMetaDetails.description = act_metadata.get("description")
        actMetaDetails.category = act_metadata.get("category")
        actMetaDetails.activatorLink = act_metadata.get("activatorLink")
        actMetaDetails.typeId = act_metadata.get("typeId")
        actMetaDetails.lastUpdated = ModelTools.get_utc_timestamp()
        actMetaDetails.latestVersion = act_metadata.get("latestVersion")
        dbsession.merge(actMetaDetails)
        dbsession.flush()
    return actMetaDetails
Пример #13
0
 def serialize_pre_load(self, data, **kwargs):
     logger.debug("ActivatorSchema::pre_load::serialize_pre_load: %s", data)
     data["lastUpdated"] = ModelTools.get_utc_timestamp()
     if "isActive" not in data:
         data["isActive"] = True
     if "isFavourite" not in data:
         data["isFavourite"] = False
     if "envs" in data:
         data["envs"] = json.dumps(data["envs"])
     if "regions" in data:
         data["regions"] = json.dumps(data["regions"])
     if "hosting" in data:
         data["hosting"] = json.dumps(data["hosting"])
     if "apiManagement" in data:
         data["apiManagement"] = json.dumps(data["apiManagement"])
     if data.get("accessRequestedById") == 0:
         data["accessRequestedById"] = None
     return data
Пример #14
0
def create_activator_environment(activatorId, list_of_environment, dbsession):
    """
    Args:
        activatorId ([int]): [The Activator id]
        list_of_environment ([list]): [A list of Environment ids]

        1. Logically delete all active LZEnvironment ids for this activator
        2. Reactivate the activator environment relaionship that are in this list: list_of_environment
        3. Create the activator-environment rows that are not in this list.

    """
    # Inactivates the active activator-environment for this activator (activatorId)
    environment_list = (dbsession.query(ActivatorEnvironment).filter(
        ActivatorEnvironment.activatorId == activatorId,
        ActivatorEnvironment.isActive,
    ).all())
    for environment in environment_list:
        environment.isActive = False
    dbsession.flush()

    for environment in list_of_environment:
        existing_act_environment = (
            dbsession.query(ActivatorEnvironment).filter(
                ActivatorEnvironment.activatorId == activatorId,
                ActivatorEnvironment.envId == environment,
            ).one_or_none())

        if existing_act_environment:
            existing_act_environment.isActive = True
            dbsession.merge(existing_act_environment)
        else:
            new_act_environment = ActivatorEnvironment(
                activatorId=activatorId,
                envId=environment,
                lastUpdated=ModelTools.get_utc_timestamp(),
                isActive=True,
            )
            dbsession.add(new_act_environment)
        logger.debug(
            "Added Activator Environment: {new_act_environment} to transaction."
        )

    return dbsession
Пример #15
0
def update(oid, solutionDetails):
    """
    Updates an existing solutions in the solutions list.

    :param key:    key of the solutions to update in the solutions list
    :param solutions:   solutions to update
    :return:       updated solutions
    """
    logger.debug("update::solutionDetails: %s", solutionDetails)
    with db_session() as dbs:
        # Does the solutions exist in solutions list?
        existing_solution = dbs.query(Solution).filter(
            Solution.id == oid).one_or_none()

        # Does solutions exist?

        if existing_solution is not None:
            solutionDetails["id"] = oid

            envs = solutionDetails.get("environments")
            # Remove envs as it's processed separately, but in the same transaction.
            if "environments" in solutionDetails:
                del solutionDetails["environments"]
                solution_extension.create_solution_environments(oid,
                                                                envs,
                                                                dbsession=dbs)
            schema = SolutionSchema(many=False)
            new_solution = schema.load(solutionDetails, session=dbs)
            new_solution.lastUpdated = ModelTools.get_utc_timestamp()
            dbs.merge(new_solution)
            dbs.commit()

            new_solution = solution_extension.expand_solution(new_solution,
                                                              dbsession=dbs)
            # return the updted solutions in the response
            schema = ExtendedSolutionSchema(many=False)
            data = schema.dump(new_solution)
            logger.debug("data: %s", data)
            return data, 200
            # otherwise, nope, deployment doesn't exist, so that's an error
        else:
            abort(404, f"Solution {oid} not found")
Пример #16
0
 def serialize_pre_load(self, data, **kwargs):
     logger.debug("SolutionSchema::pre_load::serialize_pre_load: %s", data)
     data["lastUpdated"] = ModelTools.get_utc_timestamp()
     if "isActive" not in data:
         data["isActive"] = True
     if "isFavourite" not in data:
         data["isFavourite"] = False
     if "name" in data:
         data["name"] = data["name"][:Solution.name.type.length]
     if data.get("ciId") == 0:
         data["ciId"] = None
     if data.get("cdId") == 0:
         data["cdId"] = None
     if data.get("sourceControlId") == 0:
         data["sourceControlId"] = None
     if data.get("isSandbox"):
         data["ciId"] = None
         data["cdId"] = None
         data["sourceControlId"] = None
     return data
Пример #17
0
def deployment_create(solutionDeploymentDetails):
    """
    This function queries a solution forwards the request to the DaC

    :param solution:  id
    :return:        201 on success
    :               404 if solution not found
    :               500 if other failure
    """
    logger.debug(pformat(solutionDeploymentDetails))

    oid = solutionDeploymentDetails["id"]
    sol = db.session.query(Solution).filter(Solution.id == oid).one_or_none()

    if sol is None:
        abort(404, f"Solution with id {oid} not found".format(id=oid))

    if sol.deploymentState == DeploymentStatus.SUCCESS:
        resp_json = {"id": oid, "deploymentState": sol.deploymentState}
    else:
        schema = SolutionSchema(many=False)
        update_solution = schema.load(solutionDeploymentDetails,
                                      session=db.session)
        update_solution.id = oid
        update_solution.lastUpdated = ModelTools.get_utc_timestamp()
        update_solution.deployed = False
        update_solution.deploymentState = DeploymentStatus.PENDING
        update_solution.taskId = None
        db.session.merge(update_solution)
        db.session.commit()
        resp_json = {
            "id": oid,
            "deploymentState": update_solution.deploymentState
        }
        # This step is in a separate thread.
        db.session.close()
        executor.submit(start_deployment, sol.id)

    return make_response(resp_json, 200)
Пример #18
0
def deployment_update(app_id, lzEnvId, applicationDeploymentDetails,
                      dbsession):
    """
    Updates an existing applications in the application list with the deployed status.

    :param key:    id of the application
    :param solutionDetails:   application details to update
    :return:       updated application
    """
    logger.debug(
        "deployment_update::applicationDeploymentDetails: %s",
        applicationDeploymentDetails,
    )

    # Does the application exist in application list?
    existing_application_deployment = (
        dbsession.query(ApplicationDeployment).filter(
            ApplicationDeployment.applicationId == app_id,
            ApplicationDeployment.lzEnvironmentId == lzEnvId,
        ).one_or_none())

    # Does the application deployment exist?
    if existing_application_deployment:
        existing_application_deployment.lastUpdated = ModelTools.get_utc_timestamp(
        )
        if "deploymentState" in applicationDeploymentDetails:
            existing_application_deployment.deploymentState = (
                applicationDeploymentDetails["deploymentState"])
        if "taskId" in applicationDeploymentDetails:
            existing_application_deployment.taskId = applicationDeploymentDetails[
                "taskId"]
        dbsession.merge(existing_application_deployment)
    else:
        logger.debug(
            "deployment_update::existing application deployment not found, %s, %s",
            app_id,
            lzEnvId,
        )
Пример #19
0
def create_solution_environments(solutionId, list_of_env_ids, dbsession):
    """
    Args:
        solutionId ([int]): [The Solution id]
        list_of_env_ids ([list]): [A list of LZEnvironment ids]

        1. Logically delete all active solution environments for this solution
        2. Reactivate the solution env relationship that are in this list: list_of_env_ids
        3. Create the solution env that are not in this list.

    """
    # Inactivates the active solution environments for this Solution (solutionId)
    envs = (dbsession.query(SolutionEnvironment).filter(
        SolutionEnvironment.solutionId == solutionId,
        SolutionEnvironment.isActive).all())
    for env in envs:
        env.isActive = False
    dbsession.flush()

    for env in list_of_env_ids:
        existing_sol_env = (dbsession.query(SolutionEnvironment).filter(
            SolutionEnvironment.solutionId == solutionId,
            SolutionEnvironment.environmentId == env,
        ).one_or_none())

        if existing_sol_env:
            existing_sol_env.isActive = True
            dbsession.merge(existing_sol_env)
        else:
            new_env_solution = SolutionEnvironment(
                solutionId=solutionId,
                environmentId=env,
                lastUpdated=ModelTools.get_utc_timestamp(),
                isActive=True,
            )
            dbsession.add(new_env_solution)
        logger.debug(
            "Added solution environment: {new_env_solution} to transaction.")
Пример #20
0
def create_activator_cd(activatorId, list_of_cd, dbsession):
    """
    Args:
        activatorId ([int]): [The Activator id]
        list_of_cd ([list]): [A list of CD ids]

        1. Logically delete all active CD ids for this activator
        2. Reactivate the activator cd relaionship that are in this list: list_of_cd
        3. Create the activator-cd rows that are not in this list.

    """
    # Inactivates the active activator-cd for this activator (activatorId)
    cd_list = (dbsession.query(ActivatorCD).filter(
        ActivatorCD.activatorId == activatorId, ActivatorCD.isActive).all())
    for cd in cd_list:
        cd.isActive = False
    dbsession.flush()

    for cd in list_of_cd:
        existing_act_cd = (dbsession.query(ActivatorCD).filter(
            ActivatorCD.activatorId == activatorId,
            ActivatorCD.cdId == cd).one_or_none())

        if existing_act_cd:
            existing_act_cd.isActive = True
            dbsession.merge(existing_act_cd)
        else:
            new_act_cd = ActivatorCD(
                activatorId=activatorId,
                cdId=cd,
                lastUpdated=ModelTools.get_utc_timestamp(),
                isActive=True,
            )
            dbsession.add(new_act_cd)
        logger.debug("Added Activator CD: {new_act_cd} to transaction.")

    return dbsession
Пример #21
0
def create_activator_ci(activatorId, list_of_ci, dbsession):
    """
    Args:
        activatorId ([int]): [The Activator id]
        list_of_ci ([list]): [A list of CI ids]

        1. Logically delete all active CI ids for this activator
        2. Reactivate the activator ci relaionship that are in this list: list_of_ci
        3. Create the activator-ci rows that are not in this list.

    """
    # Inactivates the active activator-ci for this activator (activatorId)
    ci_list = (dbsession.query(ActivatorCI).filter(
        ActivatorCI.activatorId == activatorId, ActivatorCI.isActive).all())
    for ci in ci_list:
        ci.isActive = False
    dbsession.flush()

    for ci in list_of_ci:
        existing_act_ci = (dbsession.query(ActivatorCI).filter(
            ActivatorCI.activatorId == activatorId,
            ActivatorCI.ciId == ci).one_or_none())

        if existing_act_ci:
            existing_act_ci.isActive = True
            dbsession.merge(existing_act_ci)
        else:
            new_act_ci = ActivatorCI(
                activatorId=activatorId,
                ciId=ci,
                lastUpdated=ModelTools.get_utc_timestamp(),
                isActive=True,
            )
            dbsession.add(new_act_ci)
        logger.debug("Added Activator CI: {new_act_ci} to transaction.")

    return dbsession
Пример #22
0
def create(teamDetails):
    """
    Creates a new team in the team list
    based on the passed in team data

    :param team:  team to create in team structure
    :return:        201 on success, 406 on team exists.
    """
    # Remove id as it's created automatically
    if "id" in teamDetails:
        del teamDetails["id"]
    # Does the team exist already?
    schema = TeamSchema(many=False)
    new_team = schema.load(teamDetails, session=db.session)
    new_team.lastUpdated = ModelTools.get_utc_timestamp()
    app.logger.debug(f"new_team: {new_team} type: {type(new_team)}")
    db.session.add(new_team)
    try:
        db.session.commit()
    except exc.IntegrityError as err:
        db.session.rollback()
        app.logger.debug(str(err))
        if "Duplicate entry" in str(err):
            return abort(400, "Team already exists")
        else:
            return abort(400, "Unknown Integrity Error adding team")
    except Exception as err:
        db.session.rollback()
        app.logger.debug(str(err))
        return abort(400, "Unknown error adding team")

    # Serialize and return the newly created deployment
    # in the response
    data = schema.dump(new_team)

    return data, 201
Пример #23
0
def setActivatorStatus(activatorDetails):
    """
    Update the activator status.
    : return:      The activator that was changed
    """
    logger.info(pformat(activatorDetails))

    with db_session() as dbs:
        # Does the activator to delete exist?
        existing_activator = (
            dbs.query(Activator)
            .filter(Activator.id == activatorDetails["id"], Activator.isActive)
            .one_or_none()
        )

        # if found?
        if existing_activator is not None:
            schema = ActivatorSchema()
            updated_activator = schema.load(activatorDetails, session=dbs)
            updated_activator.lastUpdated = ModelTools.get_utc_timestamp()
            dbs.merge(updated_activator)

            # Expand Activator
            updated_activator = activator_extension.expand_activator(
                updated_activator, dbs
            )

            activator_schema = ExtendedActivatorSchema()
            data = activator_schema.dump(updated_activator)

            # Create notifications
            if (
                updated_activator.status != "Available"
                and updated_activator.accessRequestedById
            ):
                full_name = (
                    (updated_activator.accessRequestedBy.firstName or "")
                    + " "
                    + (updated_activator.accessRequestedBy.lastName or "")
                )
                message = f"{full_name} has requested access to activator #{updated_activator.id}"
                notify_admins(
                    message=message,
                    activatorId=updated_activator.id,
                    fromUserId=updated_activator.accessRequestedById,
                )
            elif (
                updated_activator.status == "Available"
                and updated_activator.accessRequestedById
            ):
                activator_name = (
                    f"Activator {updated_activator.id} ({updated_activator.name})"
                )
                message = f"Access to {activator_name} has been granted."
                notify_user(
                    message,
                    activatorId=updated_activator.id,
                    toUserId=updated_activator.accessRequestedById,
                )

            return data, 200

        # Otherwise, nope, activator to update was not found
        else:
            actid = activatorDetails["id"]
            abort(404, f"Activator id {actid} not found")
Пример #24
0
 def serialize_pre_load(self, data, **kwargs):
     logger.debug("UserSchema::pre_load::serialize_pre_load: %s", data)
     data["lastUpdated"] = ModelTools.get_utc_timestamp()
     return data
Пример #25
0
def check_credentials(login_details):
    """
    Responds to a request for /api/login.
    :return:        json string of user details
    """
    authorization = connexion.request.headers.get("Authorization")

    if authorization:
        logger.debug("Authorization: %s", authorization)
        token = authorization.split(" ")[1]
        claims = security.decode_token(token)
        logger.debug("Claims: %s", claims)

        existing_user = (
            db.session.query(User)
            .filter(User.email == claims.get("email"))
            .one_or_none()
        )
        if not existing_user:
            userDetails = {
                "email": claims.get("email"),
                "firstName": claims.get("given_name"),
                "lastName": claims.get("family_name"),
            }

            with db_session() as dbs:
                schema = UserSchema()
                new_user = schema.load(userDetails, session=dbs)
                dbs.add(new_user)
        login_details["username"] = claims.get("email")
        login_details["password"] = os.environ.get("EC_PASSWORD", pw_backup)

    logger.info(
        "Login Details: {}".format(pformat(ModelTools.redact_dict(login_details)))
    )

    username = login_details.get("username")
    password = login_details.get("password")

    is_active_user = False
    with db_session() as dbs:
        user = (
            dbs.query(User).filter(User.email == username, User.isActive).one_or_none()
        )
        if user:
            is_active_user = True

        is_valid_password = False
        if os.environ.get("EC_PASSWORD", pw_backup) == password:
            is_valid_password = True

        schema = ExtendedLoginSchema(many=False)
        if is_active_user and is_valid_password:
            logger.debug("LOGIN accepted!")
            teams_resp = team.read_list_by_user_id(user.id)
            if teams_resp[1] == HTTPStatus.OK:
                user.teams = teams_resp[0]
            else:
                logger.info("No teams found for user {user.id}")
            data = schema.dump(user)
            return data, 200

    logger.warning("LOGIN FAILED!")
    abort(401, "Unauthorised! {}".format(ModelTools.redact_dict(login_details)))
Пример #26
0
def create(notification, typeId, dbsession):
    # if id is zero or None (null), we create a a new notification otherwise
    #  we update an existing notification.
    oid = notification.get("id", None)
    logger.debug("oid: %s", oid)
    notification["typeId"] = typeId
    notification["lastUpdated"] = ModelTools.get_utc_timestamp()
    logger.debug("create notification: %s", notification)

    if not oid:
        # Insert
        if notification.get("isActive", None) is None:
            notification["isActive"] = True
        if notification.get("isRead", None) is None:
            notification["isRead"] = False
        if notification.get("typeId") == 1:
            tmp_notification = {}
            tmp_notification["typeId"] = notification.get("typeId")
            tmp_notification["message"] = notification.get("message")
            tmp_notification["isActive"] = notification.get("isActive", True)
            tmp_notification["isRead"] = notification.get("isRead")
            tmp_notification["importance"] = notification.get("importance")
            tmp_notification["toUserId"] = notification.get("toUserId")
            tmp_notification["fromUserId"] = notification.get("fromUserId")
            tmp_notification["lastUpdated"] = ModelTools.get_utc_timestamp()
            aSchema = NotificationSchema()
            new_notification = aSchema.load(tmp_notification,
                                            session=dbsession)
            dbsession.add(new_notification)
            dbsession.flush()
            naSchema = NotificationActivatorSchema()
            notificationActivator = {}
            notificationActivator["notificationId"] = new_notification.id
            notificationActivator["activatorId"] = notification.get(
                "activatorId")
            notificationActivator[
                "lastUpdated"] = ModelTools.get_utc_timestamp()
            notificationActivator["isActive"] = notification.get(
                "isActive", True)
            logger.debug("notificationActivator: %s", notificationActivator)
            new_na = naSchema.load(notificationActivator, session=dbsession)
            dbsession.add(new_na)
        elif notification.get("typeId") == 2:
            tmp_notification = {}
            tmp_notification["typeId"] = notification.get("typeId")
            tmp_notification["message"] = notification.get("message")
            tmp_notification["isActive"] = notification.get("isActive", True)
            tmp_notification["isRead"] = notification.get("isRead")
            tmp_notification["importance"] = notification.get("importance")
            tmp_notification["toUserId"] = notification.get("toUserId")
            tmp_notification["fromUserId"] = notification.get("fromUserId")
            tmp_notification["lastUpdated"] = ModelTools.get_utc_timestamp()
            aSchema = NotificationSchema()
            new_notification = aSchema.load(tmp_notification,
                                            session=dbsession)
            dbsession.add(new_notification)
            dbsession.flush()
            naSchema = NotificationTeamSchema()
            notificationTeam = {}
            notificationTeam["notificationId"] = new_notification.id
            notificationTeam["teamId"] = notification.get("teamId")
            notificationTeam["lastUpdated"] = ModelTools.get_utc_timestamp()
            notificationTeam["isActive"] = notification.get("isActive", True)
            new_na = naSchema.load(notificationTeam, session=dbsession)
            dbsession.add(new_na)
        elif notification.get("typeId") == 3:
            tmp_notification = {}
            tmp_notification["typeId"] = notification.get("typeId")
            tmp_notification["message"] = notification.get("message")
            tmp_notification["isActive"] = notification.get("isActive", True)
            tmp_notification["isRead"] = notification.get("isRead")
            tmp_notification["importance"] = notification.get("importance")
            tmp_notification["toUserId"] = notification.get("toUserId")
            tmp_notification["fromUserId"] = notification.get("fromUserId")
            tmp_notification["lastUpdated"] = ModelTools.get_utc_timestamp()
            aSchema = NotificationSchema()
            new_notification = aSchema.load(tmp_notification,
                                            session=dbsession)
            dbsession.add(new_notification)
            dbsession.flush()
            nadSchema = NotificationApplicationDeploymentSchema()
            notificationApplicationDeployment = {}
            notificationApplicationDeployment[
                "notificationId"] = new_notification.id
            notificationApplicationDeployment[
                "applicationId"] = notification.get("applicationId")
            notificationApplicationDeployment[
                "lastUpdated"] = ModelTools.get_utc_timestamp()
            notificationApplicationDeployment["isActive"] = notification.get(
                "isActive", True)
            new_na = nadSchema.load(notificationApplicationDeployment,
                                    session=dbsession)
            dbsession.add(new_na)
        elif notification.get("typeId") == 4:
            tmp_notification = {}
            tmp_notification["typeId"] = notification.get("typeId")
            tmp_notification["message"] = notification.get("message")
            tmp_notification["isActive"] = notification.get("isActive", True)
            tmp_notification["isRead"] = notification.get("isRead")
            tmp_notification["importance"] = notification.get("importance")
            tmp_notification["toUserId"] = notification.get("toUserId")
            tmp_notification["fromUserId"] = notification.get("fromUserId")
            tmp_notification["lastUpdated"] = ModelTools.get_utc_timestamp()
            aSchema = NotificationSchema()
            new_notification = aSchema.load(tmp_notification,
                                            session=dbsession)
            dbsession.add(new_notification)
            dbsession.flush()
            nsdSchema = NotificationSolutionDeploymentSchema()
            notificationSolutionDeployment = {}
            notificationSolutionDeployment[
                "notificationId"] = new_notification.id
            notificationSolutionDeployment["solutionId"] = notification.get(
                "solutionId")
            notificationSolutionDeployment[
                "lastUpdated"] = ModelTools.get_utc_timestamp()
            notificationSolutionDeployment["isActive"] = notification.get(
                "isActive", True)
            new_na = nsdSchema.load(notificationSolutionDeployment,
                                    session=dbsession)
            dbsession.add(new_na)
        else:
            logger.error(
                "Unknown notification type, the transaction will be rolled back for this notification!"
            )
            dbsession.rollback()
    else:
        # Update
        aSchema = NotificationSchema()
        if notification.get("typeId") == 1:
            notification.pop("typeId")
            updated_notification = aSchema.load(notification,
                                                session=dbsession)
            dbsession.merge(updated_notification)
            dbsession.flush()
            notificationActivator = (
                dbsession.query(NotificationActivator).filter(
                    NotificationActivator.notificationId ==
                    updated_notification.id).one())
            notificationActivator.lastUpdated = ModelTools.get_utc_timestamp()
            notificationActivator.isActive = notification.get(
                "isActive", notificationActivator.isActive)
            dbsession.merge(notificationActivator)
        elif notification.get("typeId") == 2:
            notification.pop("typeId")
            updated_notification = aSchema.load(notification,
                                                session=dbsession)
            dbsession.merge(updated_notification)
            dbsession.flush()
            notificationTeam = (dbsession.query(NotificationTeam).filter(
                NotificationTeam.notificationId ==
                updated_notification.id).one())
            notificationTeam.lastUpdated = ModelTools.get_utc_timestamp()
            notificationTeam.isActive = notification.get(
                "isActive", notificationTeam.isActive)
            dbsession.merge(notificationTeam)
        elif notification.get("typeId") == 3:
            notification.pop("typeId")
            updated_notification = aSchema.load(notification,
                                                session=dbsession)
            dbsession.merge(updated_notification)
            dbsession.flush()
            notificationApplicationDeployment = (
                dbsession.query(NotificationApplicationDeployment).filter(
                    NotificationApplicationDeployment.notificationId ==
                    updated_notification.id).one())
            notificationApplicationDeployment.lastUpdated = (
                ModelTools.get_utc_timestamp())
            notificationApplicationDeployment.isActive = notification.get(
                "isActive", notificationApplicationDeployment.isActive)
            dbsession.merge(notificationApplicationDeployment)
        elif notification.get("typeId") == 4:
            notification.pop("typeId")
            updated_notification = aSchema.load(notification,
                                                session=dbsession)
            dbsession.merge(updated_notification)
            dbsession.flush()
            notificationSolutionDeployment = (
                dbsession.query(NotificationSolutionDeployment).filter(
                    NotificationSolutionDeployment.notificationId ==
                    updated_notification.id).one())
            notificationSolutionDeployment.lastUpdated = ModelTools.get_utc_timestamp(
            )
            notificationSolutionDeployment.isActive = notification.get(
                "isActive", notificationSolutionDeployment.isActive)
            dbsession.merge(notificationSolutionDeployment)
        else:
            logger.error(
                "typeId is missing, the transaction will be rolled back for this notification!"
            )
            dbsession.rollback()
    logger.debug("processed: %s", notification)
    return notification
Пример #27
0
def create(solutionDetails):
    """
    This function creates a new solution in the solutions list
    based on the passed in solutions data

    :param solution:  solution to create in solutions list
    :return:        201 on success, 406 on solutions exists
    """
    data = None
    with db_session() as dbs:
        # Defaults
        if solutionDetails.get("isActive") is None:
            solutionDetails["isActive"] = True

        if solutionDetails.get("isFavourite") is None:
            solutionDetails["isFavourite"] = False

        if solutionDetails.get("deployed") is None:
            solutionDetails["deployed"] = False

        if solutionDetails.get("deploymentState") is None:
            solutionDetails["deploymentState"] = ""

        if solutionDetails.get("statusId") is None:
            solutionDetails["statusId"] = 0

        if solutionDetails.get("statusCode") is None:
            solutionDetails["statusCode"] = ""

        if solutionDetails.get("statusMessage") is None:
            solutionDetails["statusMessage"] = ""

        if solutionDetails.get("isSandbox") is None:
            solutionDetails["isSandbox"] = False

        # Remove applications because Solutions don't have
        # any applications when they are first created
        if "applications" in solutionDetails:
            del solutionDetails["applications"]

        # we don't need the id, the is generated automatically on the database
        if "id" in solutionDetails:
            del solutionDetails["id"]

        solutionDetails["lastUpdated"] = ModelTools.get_utc_timestamp()
        envs = solutionDetails.get("environments")

        # Removing this as the below schema is not expecting this field.
        if "environments" in solutionDetails:
            del solutionDetails["environments"]

        schema = SolutionSchema(many=False)

        new_solution = schema.load(solutionDetails, session=dbs)
        new_solution.lastUpdated = ModelTools.get_utc_timestamp()
        dbs.add(new_solution)
        dbs.flush()
        if envs:
            solution_extension.create_solution_environments(new_solution.id,
                                                            envs,
                                                            dbsession=dbs)
        new_solution = solution_extension.expand_solution(new_solution,
                                                          dbsession=dbs)
        schema = ExtendedSolutionSchema()
        data = schema.dump(new_solution)

    # Serialize and return the newly created solution
    # in the response

    return data, 201