Search in sources :

Example 1 with APICommand

use of org.apache.cloudstack.api.APICommand in project cloudstack by apache.

the class ApiDispatcher method doAccessChecks.

private void doAccessChecks(BaseCmd cmd, Map<Object, AccessType> entitiesToAccess) {
    Account caller = CallContext.current().getCallingAccount();
    APICommand commandAnnotation = cmd.getClass().getAnnotation(APICommand.class);
    String apiName = commandAnnotation != null ? commandAnnotation.name() : null;
    if (!entitiesToAccess.isEmpty()) {
        for (Object entity : entitiesToAccess.keySet()) {
            if (entity instanceof ControlledEntity) {
                _accountMgr.checkAccess(caller, entitiesToAccess.get(entity), false, apiName, (ControlledEntity) entity);
            } else if (entity instanceof InfrastructureEntity) {
            // FIXME: Move this code in adapter, remove code from Account manager
            }
        }
    }
}
Also used : Account(com.cloud.user.Account) ControlledEntity(org.apache.cloudstack.acl.ControlledEntity) InfrastructureEntity(org.apache.cloudstack.acl.InfrastructureEntity) APICommand(org.apache.cloudstack.api.APICommand)

Example 2 with APICommand

use of org.apache.cloudstack.api.APICommand in project cloudstack by apache.

the class ApiServer method start.

@Override
public boolean start() {
    Security.addProvider(new BouncyCastleProvider());
    // api port, null by default
    Integer apiPort = IntegrationAPIPort.value();
    final Long snapshotLimit = ConcurrentSnapshotsThresholdPerHost.value();
    if (snapshotLimit == null || snapshotLimit.longValue() <= 0) {
        s_logger.debug("Global concurrent snapshot config parameter " + ConcurrentSnapshotsThresholdPerHost.value() + " is less or equal 0; defaulting to unlimited");
    } else {
        dispatcher.setCreateSnapshotQueueSizeLimit(snapshotLimit);
    }
    final Long migrationLimit = VolumeApiService.ConcurrentMigrationsThresholdPerDatastore.value();
    if (migrationLimit == null || migrationLimit.longValue() <= 0) {
        s_logger.debug("Global concurrent migration config parameter " + VolumeApiService.ConcurrentMigrationsThresholdPerDatastore.value() + " is less or equal 0; defaulting to unlimited");
    } else {
        dispatcher.setMigrateQueueSizeLimit(migrationLimit);
    }
    final Set<Class<?>> cmdClasses = new HashSet<Class<?>>();
    for (final PluggableService pluggableService : pluggableServices) {
        cmdClasses.addAll(pluggableService.getCommands());
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Discovered plugin " + pluggableService.getClass().getSimpleName());
        }
    }
    for (final Class<?> cmdClass : cmdClasses) {
        final APICommand at = cmdClass.getAnnotation(APICommand.class);
        if (at == null) {
            throw new CloudRuntimeException(String.format("%s is claimed as a API command, but it doesn't have @APICommand annotation", cmdClass.getName()));
        }
        String apiName = at.name();
        List<Class<?>> apiCmdList = s_apiNameCmdClassMap.get(apiName);
        if (apiCmdList == null) {
            apiCmdList = new ArrayList<Class<?>>();
            s_apiNameCmdClassMap.put(apiName, apiCmdList);
        }
        apiCmdList.add(cmdClass);
    }
    setEncodeApiResponse(EncodeApiResponse.value());
    if (apiPort != null) {
        final ListenerThread listenerThread = new ListenerThread(this, apiPort);
        listenerThread.start();
    }
    return true;
}
Also used : PluggableService(com.cloud.utils.component.PluggableService) APICommand(org.apache.cloudstack.api.APICommand) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) HashSet(java.util.HashSet)

Example 3 with APICommand

use of org.apache.cloudstack.api.APICommand in project cloudstack by apache.

the class ApiXmlDocWriter method main.

public static void main(String[] args) {
    Set<Class<?>> cmdClasses = ReflectUtil.getClassesWithAnnotation(APICommand.class, new String[] { "org.apache.cloudstack.api", "com.cloud.api", "com.cloud.api.commands", "com.globo.globodns.cloudstack.api", "org.apache.cloudstack.network.opendaylight.api", "org.apache.cloudstack.api.command.admin.zone", "org.apache.cloudstack.network.contrail.api.command" });
    for (Class<?> cmdClass : cmdClasses) {
        if (cmdClass.getAnnotation(APICommand.class) == null) {
            System.out.println("Warning, API Cmd class " + cmdClass.getName() + " has no APICommand annotation ");
            continue;
        }
        String apiName = cmdClass.getAnnotation(APICommand.class).name();
        if (s_apiNameCmdClassMap.containsKey(apiName)) {
            // handle API cmd separation into admin cmd and user cmd with the common api name
            Class<?> curCmd = s_apiNameCmdClassMap.get(apiName);
            if (curCmd.isAssignableFrom(cmdClass)) {
                // api_cmd map always keep the admin cmd class to get full response and parameters
                s_apiNameCmdClassMap.put(apiName, cmdClass);
            } else if (cmdClass.isAssignableFrom(curCmd)) {
                // just skip this one without warning
                continue;
            } else {
                System.out.println("Warning, API Cmd class " + cmdClass.getName() + " has non-unique apiname " + apiName);
                continue;
            }
        } else {
            s_apiNameCmdClassMap.put(apiName, cmdClass);
        }
    }
    System.out.printf("Scanned and found %d APIs\n", s_apiNameCmdClassMap.size());
    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    while (iter.hasNext()) {
        String arg = iter.next();
        if (arg.equals("-d")) {
            s_dirName = iter.next();
        }
    }
    for (Map.Entry<String, Class<?>> entry : s_apiNameCmdClassMap.entrySet()) {
        Class<?> cls = entry.getValue();
        s_allApiCommands.put(entry.getKey(), cls.getName());
    }
    s_allApiCommandsSorted.putAll(s_allApiCommands);
    try {
        // Create object writer
        XStream xs = new XStream();
        xs.alias("command", Command.class);
        xs.alias("arg", Argument.class);
        String xmlDocDir = s_dirName + "/xmldoc";
        String rootAdminDirName = xmlDocDir + "/apis";
        (new File(rootAdminDirName)).mkdirs();
        ObjectOutputStream out = xs.createObjectOutputStream(new FileWriter(s_dirName + "/commands.xml"), "commands");
        ObjectOutputStream rootAdmin = xs.createObjectOutputStream(new FileWriter(rootAdminDirName + "/" + "apiSummary.xml"), "commands");
        ObjectOutputStream rootAdminSorted = xs.createObjectOutputStream(new FileWriter(rootAdminDirName + "/" + "apiSummarySorted.xml"), "commands");
        Iterator<?> it = s_allApiCommands.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            // Write admin commands
            writeCommand(out, key);
            writeCommand(rootAdmin, key);
            // Write single commands to separate xml files
            ObjectOutputStream singleRootAdminCommandOs = xs.createObjectOutputStream(new FileWriter(rootAdminDirName + "/" + key + ".xml"), "command");
            writeCommand(singleRootAdminCommandOs, key);
            singleRootAdminCommandOs.close();
        }
        // Write sorted commands
        it = s_allApiCommandsSorted.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            writeCommand(rootAdminSorted, key);
        }
        out.close();
        rootAdmin.close();
        rootAdminSorted.close();
        // write alerttypes to xml
        writeAlertTypes(xmlDocDir);
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(2);
    }
}
Also used : XStream(com.thoughtworks.xstream.XStream) FileWriter(java.io.FileWriter) ObjectOutputStream(java.io.ObjectOutputStream) APICommand(org.apache.cloudstack.api.APICommand) IOException(java.io.IOException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) File(java.io.File)

Example 4 with APICommand

use of org.apache.cloudstack.api.APICommand in project cloudstack by apache.

the class AccountManagerImpl method createApiNameList.

protected List<String> createApiNameList(Set<Class<?>> cmdClasses) {
    List<String> apiNameList = new ArrayList<String>();
    for (Class<?> cmdClass : cmdClasses) {
        APICommand apiCmdAnnotation = cmdClass.getAnnotation(APICommand.class);
        if (apiCmdAnnotation == null) {
            apiCmdAnnotation = cmdClass.getSuperclass().getAnnotation(APICommand.class);
        }
        if (apiCmdAnnotation == null || !apiCmdAnnotation.includeInApiDoc() || apiCmdAnnotation.name().isEmpty()) {
            continue;
        }
        String apiName = apiCmdAnnotation.name();
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("Found api: " + apiName);
        }
        apiNameList.add(apiName);
    }
    return apiNameList;
}
Also used : ArrayList(java.util.ArrayList) APICommand(org.apache.cloudstack.api.APICommand)

Example 5 with APICommand

use of org.apache.cloudstack.api.APICommand in project cloudstack by apache.

the class RoleBasedAPIAccessChecker method start.

@Override
public boolean start() {
    for (RoleType role : RoleType.values()) {
        Long policyId = getDefaultPolicyId(role);
        if (policyId != null) {
            _iamSrv.resetIAMPolicy(policyId);
        }
    }
    // add the system-domain capability
    _iamSrv.addIAMPermissionToIAMPolicy(new Long(Account.ACCOUNT_TYPE_ADMIN + 1), null, null, null, "SystemCapability", null, Permission.Allow, false);
    _iamSrv.addIAMPermissionToIAMPolicy(new Long(Account.ACCOUNT_TYPE_DOMAIN_ADMIN + 1), null, null, null, "DomainCapability", null, Permission.Allow, false);
    _iamSrv.addIAMPermissionToIAMPolicy(new Long(Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN + 1), null, null, null, "DomainResourceCapability", null, Permission.Allow, false);
    // add permissions for public templates
    List<VMTemplateVO> pTmplts = _templateDao.listByPublic();
    for (VMTemplateVO tmpl : pTmplts) {
        _iamSrv.addIAMPermissionToIAMPolicy(new Long(Account.ACCOUNT_TYPE_ADMIN + 1), VirtualMachineTemplate.class.getSimpleName(), PermissionScope.RESOURCE.toString(), tmpl.getId(), "listTemplates", AccessType.UseEntry.toString(), Permission.Allow, false);
        _iamSrv.addIAMPermissionToIAMPolicy(new Long(Account.ACCOUNT_TYPE_DOMAIN_ADMIN + 1), VirtualMachineTemplate.class.getSimpleName(), PermissionScope.RESOURCE.toString(), tmpl.getId(), "listTemplates", AccessType.UseEntry.toString(), Permission.Allow, false);
        _iamSrv.addIAMPermissionToIAMPolicy(new Long(Account.ACCOUNT_TYPE_NORMAL + 1), VirtualMachineTemplate.class.getSimpleName(), PermissionScope.RESOURCE.toString(), tmpl.getId(), "listTemplates", AccessType.UseEntry.toString(), Permission.Allow, false);
    }
    for (PluggableService service : _services) {
        for (Class<?> cmdClass : service.getCommands()) {
            APICommand command = cmdClass.getAnnotation(APICommand.class);
            if (!commandsPropertiesOverrides.contains(command.name())) {
                for (RoleType role : command.authorized()) {
                    addDefaultAclPolicyPermission(command.name(), cmdClass, role);
                }
            }
        }
    }
    for (String apiName : commandsPropertiesOverrides) {
        Class<?> cmdClass = _apiServer.getCmdClass(apiName);
        for (RoleType role : RoleType.values()) {
            if (commandsPropertiesRoleBasedApisMap.get(role).contains(apiName)) {
                // insert permission for this role for this api
                addDefaultAclPolicyPermission(apiName, cmdClass, role);
            }
        }
    }
    return super.start();
}
Also used : VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) RoleType(org.apache.cloudstack.acl.RoleType) VMTemplateVO(com.cloud.storage.VMTemplateVO) PluggableService(com.cloud.utils.component.PluggableService) APICommand(org.apache.cloudstack.api.APICommand)

Aggregations

APICommand (org.apache.cloudstack.api.APICommand)9 ArrayList (java.util.ArrayList)4 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)2 PluggableService (com.cloud.utils.component.PluggableService)2 IOException (java.io.IOException)2 Field (java.lang.reflect.Field)2 ConfigurationException (javax.naming.ConfigurationException)2 BaseCmd (org.apache.cloudstack.api.BaseCmd)2 AccountLimitException (com.cloud.exception.AccountLimitException)1 CloudAuthenticationException (com.cloud.exception.CloudAuthenticationException)1 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)1 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)1 OriginDeniedException (com.cloud.exception.OriginDeniedException)1 RequestLimitException (com.cloud.exception.RequestLimitException)1 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)1 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)1 UnavailableCommandException (com.cloud.exception.UnavailableCommandException)1