<commit_before>/*
 * Copyright 2012 Netflix, Inc.
 *
 * 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.
 */
package com.netflix.asgard

import com.amazonaws.services.autoscaling.model.AutoScalingGroup
import com.amazonaws.services.ec2.model.IpPermission
import com.amazonaws.services.ec2.model.SecurityGroup
import com.netflix.asgard.model.ApplicationInstance
import com.netflix.asgard.model.MonitorBucketType
import com.netflix.asgard.model.Owner
import grails.converters.JSON
import grails.converters.XML
import org.apache.commons.collections.Bag
import org.apache.commons.collections.HashBag

class ApplicationController {

    def applicationService
    def awsEc2Service
    def awsAutoScalingService
    def awsLoadBalancerService
    def configService
    def discoveryService

    def static allowedMethods = [save: 'POST', update: 'POST', delete: 'POST', securityUpdate: 'POST']

    def index = { redirect(action: 'list', params: params) }

    def list = {
        UserContext userContext = UserContext.of(request)
        List<AppRegistration> apps = applicationService.getRegisteredApplications(userContext)

        Bag groupCountsPerAppName = groupCountsPerAppName(userContext)
        Bag instanceCountsPerAppName = instanceCountsPerAppName(userContext)

        List<String> terms = Requests.ensureList(params.id).collect { it.split(',') }.flatten()
        Set<String> lowercaseTerms = terms*.toLowerCase() as Set
        if (terms) {
            apps = apps.findAll { AppRegistration app ->
                    app.name.toLowerCase() in lowercaseTerms ||
                    app.owner?.toLowerCase() in lowercaseTerms ||
                    app.email?.toLowerCase() in lowercaseTerms
            }
        }
        withFormat {
            html {
                [
                        applications: apps,
                        terms: terms,
                        groupCountsPerAppName: groupCountsPerAppName,
                        instanceCountsPerAppName: instanceCountsPerAppName
                ]
            }
            xml { new XML(apps).render(response) }
            json { new JSON(apps).render(response) }
        }
    }

    def owner = {
        UserContext userContext = UserContext.of(request)
        List<AppRegistration> apps = applicationService.getRegisteredApplications(userContext)
        Bag groupCountsPerAppName = groupCountsPerAppName(userContext)
        Bag instanceCountsPerAppName = instanceCountsPerAppName(userContext)
        Map<String, Owner> ownerNamesToOwners = [:]

        for (AppRegistration app in apps) {
            String ownerName = app.owner
            if (ownerNamesToOwners[ownerName] == null) {
                ownerNamesToOwners[ownerName] = new Owner(name: ownerName)
            }
            Owner owner = ownerNamesToOwners[ownerName]
            owner.emails << app.email
            owner.appNames << app.name
            owner.autoScalingGroupCount += groupCountsPerAppName.getCount(app.name)
            owner.instanceCount += instanceCountsPerAppName.getCount(app.name)
        }

        // Sort by number of instances descending, then by number of auto scaling groups descending
        List<Owner> owners = (ownerNamesToOwners.values() as List).
                sort { -1 * it.autoScalingGroupCount}.sort { -1 * it.instanceCount }

        withFormat {
            html { [owners: owners] }
            xml { new XML(owners).render(response) }
            json { new JSON(owners).render(response) }
        }
    }

    private Bag groupCountsPerAppName(UserContext userContext) {
        Collection<AutoScalingGroup> groups = awsAutoScalingService.getAutoScalingGroups(userContext)
        List<String> groupNames = groups*.autoScalingGroupName
        Bag groupCountsPerAppName = new HashBag()
        groupNames.each { groupCountsPerAppName.add(Relationships.appNameFromGroupName(it)) }
        groupCountsPerAppName
    }

    private Bag instanceCountsPerAppName(UserContext userContext) {
        Collection<ApplicationInstance> discInstances = discoveryService.getAppInstances(userContext)
        List<String> appInstanceNames = discInstances*.appName
        Bag instanceCountsPerAppName = new HashBag()
        appInstanceNames.each { instanceCountsPerAppName.add(it) }
        instanceCountsPerAppName
    }

    def show = {
        String name = params.name ?: params.id
        UserContext userContext = UserContext.of(request)
        AppRegistration app = applicationService.getRegisteredApplication(userContext, name)
        if (!app) {
            Requests.renderNotFound('Application', name, this)
        } else {
            if (log.debugEnabled) {
                log.debug "In show, name=${app.name} type=${app.type} description=${app.description}"
            }
            List<AutoScalingGroup> groups =
                    awsAutoScalingService.getAutoScalingGroupsForApp(userContext, name).sort{ it.autoScalingGroupName }
            List<String> clusterNames =
                    groups.collect { Relationships.clusterFromGroupName(it.autoScalingGroupName) }.unique()
            request.alertingServiceConfigUrl = configService.alertingServiceConfigUrl
            SecurityGroup appSecurityGroup = awsEc2Service.getSecurityGroup(userContext, name)
            def details = [
                    app: app,
                    strictName: Relationships.checkStrictName(app.name),
                    clusters: clusterNames,
                    groups: groups,
                    balancers: awsLoadBalancerService.getLoadBalancersForApp(userContext, name),
                    securities: awsEc2Service.getSecurityGroupsForApp(userContext, name),
                    appSecurityGroup: appSecurityGroup,<commit_msg>ASGARD-1030 - show Application will temporarily put a duplicate in the cache if the id has any capitalization<commit_after>/*
 * Copyright 2012 Netflix, Inc.
 *
 * 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.
 */
package com.netflix.asgard

import com.amazonaws.services.autoscaling.model.AutoScalingGroup
import com.amazonaws.services.ec2.model.IpPermission
import com.amazonaws.services.ec2.model.SecurityGroup
import com.netflix.asgard.model.ApplicationInstance
import com.netflix.asgard.model.MonitorBucketType
import com.netflix.asgard.model.Owner
import grails.converters.JSON
import grails.converters.XML
import org.apache.commons.collections.Bag
import org.apache.commons.collections.HashBag

class ApplicationController {

    def applicationService
    def awsEc2Service
    def awsAutoScalingService
    def awsLoadBalancerService
    def configService
    def discoveryService

    def static allowedMethods = [save: 'POST', update: 'POST', delete: 'POST', securityUpdate: 'POST']

    def index = { redirect(action: 'list', params: params) }

    def list = {
        UserContext userContext = UserContext.of(request)
        List<AppRegistration> apps = applicationService.getRegisteredApplications(userContext)

        Bag groupCountsPerAppName = groupCountsPerAppName(userContext)
        Bag instanceCountsPerAppName = instanceCountsPerAppName(userContext)

        List<String> terms = Requests.ensureList(params.id).collect { it.split(',') }.flatten()
        Set<String> lowercaseTerms = terms*.toLowerCase() as Set
        if (terms) {
            apps = apps.findAll { AppRegistration app ->
                    app.name.toLowerCase() in lowercaseTerms ||
                    app.owner?.toLowerCase() in lowercaseTerms ||
                    app.email?.toLowerCase() in lowercaseTerms
            }
        }
        withFormat {
            html {
                [
                        applications: apps,
                        terms: terms,
                        groupCountsPerAppName: groupCountsPerAppName,
                        instanceCountsPerAppName: instanceCountsPerAppName
                ]
            }
            xml { new XML(apps).render(response) }
            json { new JSON(apps).render(response) }
        }
    }

    def owner = {
        UserContext userContext = UserContext.of(request)
        List<AppRegistration> apps = applicationService.getRegisteredApplications(userContext)
        Bag groupCountsPerAppName = groupCountsPerAppName(userContext)
        Bag instanceCountsPerAppName = instanceCountsPerAppName(userContext)
        Map<String, Owner> ownerNamesToOwners = [:]

        for (AppRegistration app in apps) {
            String ownerName = app.owner
            if (ownerNamesToOwners[ownerName] == null) {
                ownerNamesToOwners[ownerName] = new Owner(name: ownerName)
            }
            Owner owner = ownerNamesToOwners[ownerName]
            owner.emails << app.email
            owner.appNames << app.name
            owner.autoScalingGroupCount += groupCountsPerAppName.getCount(app.name)
            owner.instanceCount += instanceCountsPerAppName.getCount(app.name)
        }

        // Sort by number of instances descending, then by number of auto scaling groups descending
        List<Owner> owners = (ownerNamesToOwners.values() as List).
                sort { -1 * it.autoScalingGroupCount}.sort { -1 * it.instanceCount }

        withFormat {
            html { [owners: owners] }
            xml { new XML(owners).render(response) }
            json { new JSON(owners).render(response) }
        }
    }

    private Bag groupCountsPerAppName(UserContext userContext) {
        Collection<AutoScalingGroup> groups = awsAutoScalingService.getAutoScalingGroups(userContext)
        List<String> groupNames = groups*.autoScalingGroupName
        Bag groupCountsPerAppName = new HashBag()
        groupNames.each { groupCountsPerAppName.add(Relationships.appNameFromGroupName(it)) }
        groupCountsPerAppName
    }

    private Bag instanceCountsPerAppName(UserContext userContext) {
        Collection<ApplicationInstance> discInstances = discoveryService.getAppInstances(userContext)
        List<String> appInstanceNames = discInstances*.appName
        Bag instanceCountsPerAppName = new HashBag()
        appInstanceNames.each { instanceCountsPerAppName.add(it) }
        instanceCountsPerAppName
    }

    def show = {
        String name = params.name ?: params.id
        name = name.toLowerCase() // Without this it could create a duplicate cache entry.
        UserContext userContext = UserContext.of(request)
        AppRegistration app = applicationService.getRegisteredApplication(userContext, name)
        if (!app) {
            Requests.renderNotFound('Application', name, this)
        } else {
            if (log.debugEnabled) {
                log.debug "In show, name=${app.name} type=${app.type} description=${app.description}"
            }
            List<AutoScalingGroup> groups =
                    awsAutoScalingService.getAutoScalingGroupsForApp(userContext, name).sort{ it.autoScalingGroupName }
            List<String> clusterNames =
                    groups.collect { Relationships.clusterFromGroupName(it.autoScalingGroupName) }.unique()
            request.alertingServiceConfigUrl = configService.alertingServiceConfigUrl
            SecurityGroup appSecurityGroup = awsEc2Service.getSecurityGroup(userContext, name)
            def details = [
                    app: app,
                    strictName: Relationships.checkStrictName(app.name),
                    clusters: clusterNames,
                    groups: groups,
                    balancers: awsLoadBalancerService.getLoadBalancersForApp(userContext, name),
                    securities: awsEc2Service.getSecurityGroupsForApp(userContext, name),
                    appSecurityGroup: appSecurityGroup,
{'fraction_non_alphanumeric': 0.07879170281567947, 'fraction_numerical': 0.0026815994952283304, 'mean_word_length': 2.6510221710336883, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6817481', 'n_tokens_mistral': 3291, 'n_tokens_neox': 3212, 'n_words': 752}