Error wsgi in server installed in MAC Yosemite

61 Views Asked by At

I have problems wsgi module and do not understand why. I installed Apache, remove MAMP because it gave me too many problems. I have configured the port and my page loads fine. Install MYSQL load my script and all is well. Install the Python-MySQL connector and make the connection and actually connects. but when I access the site and I want to register strip mistake, nose if it reaches the database or not. Someone help me understand what happens.

Attached codes.

httpd.conf

ServerRoot "/usr/local/apache2"

Listen 8080

LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule access_compat_module modules/mod_access_compat.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
LoadModule reqtimeout_module modules/mod_reqtimeout.so
LoadModule filter_module modules/mod_filter.so
LoadModule mime_module modules/mod_mime.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule env_module modules/mod_env.so
LoadModule headers_module modules/mod_headers.so
#LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule unixd_module modules/mod_unixd.so
#LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule alias_module modules/mod_alias.so
LoadModule wsgi_module modules/mod_wsgi.so

<IfModule unixd_module>

User daemon
Group daemon

</IfModule>
ServerAdmin [email protected]
ServerName localhost:8080
<Directory />
    AllowOverride none
    Require all denied
</Directory>
DocumentRoot "/Users/usuario/Sites/usuariocloud/client"
<Directory "/Users/usuario/Sites/usuariocloud/client">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

<Files ".ht*">
    Require all denied
</Files>

ErrorLog "logs/error_log"
LogLevel warn

<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    CustomLog "logs/access_log" common
</IfModule>

<IfModule alias_module>
    ScriptAlias /cgi-bin/ "/Users/usuario/Sites/usuariocloud/server/"
</IfModule>

<IfModule cgid_module>
</IfModule>

Alias /cgi-bin /Users/usuario/Sites/usuariocloud/server/
<Location /cgi-bin>
   SetHandler wsgi-script
   Options +ExecCGI
</Location>

#WSGIScriptAlias /cgi-bin /Users/usuario/Sites/usuariocloud/server/

<Directory "/Users/usuario/Sites/usuariocloud/server/">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    TypesConfig conf/mime.types

    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

</IfModule>

<IfModule proxy_html_module>
Include conf/extra/proxy-html.conf
</IfModule>

Include conf/extra/httpd-ssl.conf
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>

controller.wsgi

    # Library Imports
import json, cgi, sys, os

path =  os.path.dirname(__file__)

if path not in sys.path:
    sys.path.append(path)

# Own Libraries
from petition_solver.solver import Solver

def application(env, resp):
    response = {    "response": "fail", 
                    "error" : """Expecting ?Json=
                                {
                                    "function":"functionName",
                                    "entity":"entityName",
                                    "params":
                                    {
                                        "param1":"value1", 
                                        "param2":"value2", 
                                        "paramn":"value n"
                                    }
                                }""".replace('\r', ' ').replace('\n', ' ').replace('\t', '')   
                }

    # Read Params

    form = cgi.FieldStorage(fp=env['wsgi.input'], environ=env)

    if form:

        userAgent = env["HTTP_USER_AGENT"] if "HTTP_USER_AGENT" in env else ""
        param_json = form['json'].value

        petition = json.loads(param_json)

        if('file' in form and "params" in petition):
            param_file = form['file']

            if(isinstance(param_file, list)):
                petition['params']['files'] = []
                for f in param_file:
                    filename = unicode(f.filename, 'utf-8')
                    petition['params']['files'].append({"originalName" : filename, "file" : f.file.read()})
            else:
                petition['params']['file'] = param_file.file.read()
                filename = unicode(param_file.filename, 'utf-8')
                petition['params']['originalName'] = filename

        solver = Solver()
        response = solver.solvePetition(petition, userAgent=userAgent)

    if (response and "download" in response and response["download"]):

        detail = response["file"]["storage"]

        mime = detail["mime"].decode('utf-8')
        name = detail["originalName"].encode("ascii", 'replace')
        data = detail["file"]

        resp('200 OK',[('Content-type', '{0}'.format(mime)),('Content-disposition', 'attachment; filename*=UTF-8''{0}; filename={0}'.format(name))])
        yield data
    else:
        resp('200 OK',[('Content-type', 'text/html;charset=utf-8')])
        yield json.dumps(response)

solver.py

#solver module

#class Solver

from log import Log
from error import NotValidPetitionError

class Solver:

    userId = -1
    def solvePetition(self, petition, petitionId=0, userAgent=None):

        lg = Log.Instance()

        if("function" not in petition or "entity" not in petition):
            response = {"response":"fail",  "error" : "{0}".format(NotValidPetitionError())}
            lg.logError("Not a valid petition found", lg.SOLVER_LEVEL)
            return response

        innerPetition = self._getCopy(petition)

        function = innerPetition["function"]
        entityName = innerPetition["entity"]
        params = innerPetition["params"] if "params" in innerPetition else {}
        key = innerPetition["key"] if "key" in innerPetition else ""
        #petitionId = petitionId if petitionId else self._getPetitionId()

        #lg.logDebug("Received petition {0} ".format(self._getJsonRepr(petition)), lg.SOLVER_LEVEL, petitionId)

        entity = None
        entityType = None

        if(entityName == "user"):
            from entities.user import User
            entityType = User
            params["userAgent"] = userAgent
        elif(entityName == "group"):
            from entities.group import Group
            entityType = Group
        elif(entityName == "tag"):
            from entities.tag import Tag
            entityType = Tag        
        elif(entityName == "attribute"):
            from entities.attribute import Attribute
            entityType = Attribute
        elif(entityName == "template"):
            from entities.template import Template
            entityType = Template
        elif(entityName == "directory"):
            from entities.directory import Directory
            entityType = Directory
        elif(entityName == "staticCatalog"):
            from entities.staticCatalog import StaticCatalog
            entityType = StaticCatalog
        elif(entityName == "dynamicCatalog"):
            from entities.dynamicCatalog import DynamicCatalog
            entityType = DynamicCatalog
        elif(entityName == "document"):
            from entities.document import Document
            entityType = Document
        elif(entityName == "file"):
            from entities.file import File
            entityType = File
        elif(entityName == "inbox"):
            from entities.inbox import Inbox
            entityType = Inbox
        elif(entityName == "storageFile"):
            from entities.storageFile import StorageFile
            entityType = StorageFile
        elif(entityName == "structure"):
            from entities.structure import Structure
            entityType = Structure
        elif(entityName == "dictionaryCatalog"):
            from entities.dictionaryCatalog import DictionaryCatalog
            entityType = DictionaryCatalog
        elif(entityName == "patternTemplate"):
            from entities.patternTemplate import PatternTemplate
            entityType = PatternTemplate

        if petitionId:
            petitionId = petitionId
            valueReturned = self._operationsManager(params, petitionId, key, entityType, entityName, function, False, petition)

        else:
            petitionId = self._getPetitionId()
            valueReturned = self._operationsManager(params, petitionId, key, entityType, entityName, function, True, petition)

        lg.logDebug("Received petition {0} ".format(self._getJsonRepr(petition)), lg.SOLVER_LEVEL, petitionId)

        try:
            entity = entityType(params, key, petitionId)
            response = entity.process(function)
            pet_id = self._getPetition(entity, petitionId)
            queryUpdate = self._getDBTemplate("UPDATE_OPERATION_STATUS").format(pet_id)
            newId = entity._resolveUpdate(queryUpdate, audit=False)
            if newId > 0:
                lg.logDebug("UPDATE_PETITION_ID: {0} ".format(pet_id), lg.SOLVER_LEVEL, petitionId)
        except Exception as e:
            response = self._manageError(e, petition, petitionId)
        finally:
            del (entity)
            del (innerPetition)

        lg.logDebug("Response to petition is {0}".format(self._getJsonRepr(response)), lg.SOLVER_LEVEL, petitionId)

        response["petition"] = self._getJsonWOFile(petition)
        return response

    def _getJsonRepr(self, json):

        j = self._getJsonWOFile(json["file"]) if "file" in json else self._getJsonWOFile(json)

        return "{0}".format(j)

    def _getJsonWOFile(self, json):

        needsCopy = json and "file" in json or (
                        "params" in json and json["params"] and (
                            "file" in json["params"] or "files" in json["params"]
                        )
                    ) or "storage" in json

        if needsCopy:

            copy = self._getCopy(json)

            if ("file" in copy):
                copy["file"] = "FILE DATA OMITTED" if copy["file"] else "EMPTY FILE"

            if ("storage" in copy):
                if ("file" in copy["storage"]):
                    copy["storage"]["file"] = "FILE DATA OMITTED" if copy["storage"]["file"] else "EMPTY FILE"

            if("params" in copy):   

                if("files" in copy["params"]):
                    for f in copy['params']["files"]:
                        f["file"] = "FILE DATA OMITTED" if f["file"] else "EMPTY FILE"

                if("file" in copy["params"]):
                    copy["params"]["file"] = "FILE DATA OMITTED" if copy["params"]["file"] else "EMPTY FILE" 

            return copy

        else:
            return json

    def _getCopy(self, json):

        import copy

        copy = copy.deepcopy(json)

        return copy

    def _manageError(self, err, petition, petitionId):

        from error import usuarioError

        innerError = err if isinstance(err, usuarioError) else usuarioError()

        lg = Log.Instance()
        lgMethod = lg.logWarning if innerError.code < 400 else lg.logError
        lgMethod("{0} found while resolving petition {1}".format( str(innerError) , petitionId), lg.SOLVER_LEVEL, petitionId)

        response = {
            "response":"fail",
            "error" : {
                "code" : "{0}".format(innerError.code),
                "message" : str(innerError)
            }
        }

        return response

    def _getPetitionId(self):

        import uuid

        uuidObj = uuid.uuid4()

        return uuidObj.hex

    def _getDBTemplate(self, templateName):
        dbTemplateProvider = None
        if not dbTemplateProvider:
            from db_template_provider import DBTemplateProvider
            dbTemplateProvider = DBTemplateProvider.Instance()

        return dbTemplateProvider.getDBTemplate(templateName)

    def _findFunction(self, functionName, entityType):
        queryFunction = self._getDBTemplate("FIND_FUNCTION_ID").format(functionName)
        rows = entityType._resolveQuery(queryFunction, function=functionName, audit=False)
        if rows:
            functionId = rows[0]
            fcId = functionId[0]
            return fcId
        return 0

    def _findEntity(self, entityName, entityType):
        queryEntity = self._getDBTemplate("FIND_ENTITY_ID").format(entityName)
        rows = entityType._resolveQuery(queryEntity, audit=False)
        if rows:
            entityId = rows[0]
            entId = entityId[0]
            return entId
        return 0

    def _addOperation(self, function, entityName, entity, newId, typeOper, petitionId):
        lg = Log.Instance()
        functionId = self._findFunction(function, entity)
        entityId = self._findEntity(entityName, entity)
        queryOperation = ""
        if typeOper:
            queryOperation = self._getDBTemplate("CREATE_OPERATIONS").format(newId, functionId, entityId, 0, 2)
        else:
            queryOperation = self._getDBTemplate("CREATE_OPERATIONS").format(newId, functionId, entityId, 0, 1)
        entity._resolveUpdate(queryOperation, False)
        lg.logDebug("Operation Added: {0}".format(newId), lg.SOLVER_LEVEL, petitionId)

    def _getPetition(self, entityType, petitionId):
        queryPetition = self._getDBTemplate("FIND_PETITION_ID").format(petitionId)
        required = []
        rows = entityType._resolveQuery(queryPetition, audit=False)
        if rows:
            petId = rows[0]
            petId_ = petId[0]
            return petId_
        return 0

    def _operationsManager(self, params, petitionId, key, entityType, entityName, function, typeOper, petition):
        entity = None
        newId = 0
        lg = Log.Instance()
        try:
            entity = entityType(params, key, petitionId)

            if typeOper:
                jsonStr = self._getJsonRepr(petition).replace("\'", "\\\'")
                userName = self._findUserName(entity, key)
                if self.userId != -1:
                    queryRegistry = self._getDBTemplate("CREATE_REGISTRY_PETITIONS").format(petitionId, jsonStr, "final", 0, self.userId, userName, 5)
                    lg.logDebug("REGISTRY QUERY: {0}".format(jsonStr), lg.SOLVER_LEVEL, petitionId)
                    newId = entity._resolveUpdate(queryRegistry, audit=False)

                    if newId > 0:
                        lg.logDebug("Petition Added: {0}".format(jsonStr), lg.SOLVER_LEVEL, petitionId)
                        self._addOperation(function, entityName, entity, newId, True, petitionId)
                    else:
                        return False
                    return True
                else:
                    return False
            else:
                newId = self._getPetition(entity, petitionId)
                self._addOperation(function, entityName, entity, newId, False, petitionId)

        except Exception as e:
            lg.logError(self._manageError(e, petition, petitionId), lg.SOLVER_LEVEL, petitionId)
            return False

    def _findUserName(self, entity, key):
        userTemplate = self._getDBTemplate("QUERY_USER_BY_KEY").format(key)
        rowsId = entity._resolveQuery(userTemplate)
        if rowsId:
            self.userId = rowsId[0][0]
            nameTemplate = self._getDBTemplate("QUERY_USERNAME").format(self.userId)
            rowsUsr = entity._resolveQuery(nameTemplate)
            if rowsUsr:
                userName = rowsUsr[0][0]
                return userName
        return None

and the error isenter image description here

and the logs are the nexts

[Thu Jun 18 12:04:37.413641 2015] [wsgi:error] [pid 2048:tid 4367495168] [client ::1:49302] mod_wsgi (pid=2048): Exception occurred processing WSGI script '/Users/usuario/Sites/usuariocloud/server/controller.wsgi'., referer: http://localhost:8080/\
[Thu Jun 18 12:04:37.413692 2015] [wsgi:error] [pid 2048:tid 4367495168] [client ::1:49302] Traceback (most recent call last):, referer: http://localhost:8080/\
[Thu Jun 18 12:04:37.413719 2015] [wsgi:error] [pid 2048:tid 4367495168] [client ::1:49302]   File "/Users/usuario/Sites/usuariocloud/server/controller.wsgi", line 53, in application, referer: http://localhost:8080/\
[Thu Jun 18 12:04:37.413759 2015] [wsgi:error] [pid 2048:tid 4367495168] [client ::1:49302]     response = solver.solvePetition(petition, userAgent=userAgent), referer: http://localhost:8080/\
[Thu Jun 18 12:04:37.413775 2015] [wsgi:error] [pid 2048:tid 4367495168] [client ::1:49302]   File "/Users/usuario/Sites/usuariocloud/server/petition_solver/solver.py", line 13, in solvePetition, referer: http://localhost:8080/\
[Thu Jun 18 12:04:37.413795 2015] [wsgi:error] [pid 2048:tid 4367495168] [client ::1:49302]     lg = Log.Instance(), referer: http://localhost:8080/\
[Thu Jun 18 12:04:37.413805 2015] [wsgi:error] [pid 2048:tid 4367495168] [client ::1:49302]   File "/Users/usuario/Sites/usuariocloud/server/petition_solver/singleton.py", line 34, in Instance, referer: http://localhost:8080/\
[Thu Jun 18 12:04:37.413823 2015] [wsgi:error] [pid 2048:tid 4367495168] [client ::1:49302]     self._instance = self._decorated(), referer: http://localhost:8080/\
[Thu Jun 18 12:04:37.413833 2015] [wsgi:error] [pid 2048:tid 4367495168] [client ::1:49302]   File "/Users/usuario/Sites/usuariocloud/server/petition_solver/log.py", line 24, in __init__, referer: http://localhost:8080/\
[Thu Jun 18 12:04:37.413849 2015] [wsgi:error] [pid 2048:tid 4367495168] [client ::1:49302]     os.makedirs(directory), referer: http://localhost:8080/\
[Thu Jun 18 12:04:37.413859 2015] [wsgi:error] [pid 2048:tid 4367495168] [client ::1:49302]   File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs, referer: http://localhost:8080/\
[Thu Jun 18 12:04:37.413878 2015] [wsgi:error] [pid 2048:tid 4367495168] [client ::1:49302]     mkdir(name, mode), referer: http://localhost:8080/\
[Thu Jun 18 12:04:37.413897 2015] [wsgi:error] [pid 2048:tid 4367495168] [client ::1:49302] OSError: [Errno 13] Permission denied: '//logs', referer: http://localhost:8080/\
[Thu Jun 18 12:54:13.192665 2015] [mpm_worker:notice] [pid 2046:tid 140735125234432] AH00295: caught SIGTERM, shutting down\
1

There are 1 best solutions below

0
On

Your code is trying to write to a log file using a relative path. You cannot do that as the current working directory of the process will be '/' and not where your code is. See:

Use an absolute path explicitly, or calculate it relative to the code location by using os.path.dirname(__file__) as a base.