1
0
mirror of https://github.com/dkmstr/openuds.git synced 2025-03-20 06:50:23 +03:00

starting also proxy

This commit is contained in:
Adolfo Gómez García 2017-01-19 04:55:28 +01:00
parent ab8cb7a7e0
commit dcc870d8e0
7 changed files with 283 additions and 65 deletions

View File

@ -0,0 +1,156 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
from uds.models.CalendarRule import freqs, CalendarRule
from uds.models.Util import getSqlDatetime
from uds.core.util import log
from uds.core.util import permissions
from uds.core.util.model import processUuid
from uds.core.Environment import Environment
from uds.REST.model import DetailHandler
from uds.REST import NotFound, ResponseError, RequestError
from django.db import IntegrityError
import six
import logging
import datetime
logger = logging.getLogger(__name__)
class AccountsUsage(DetailHandler): # pylint: disable=too-many-public-methods
'''
Detail handler for Services, whose parent is a Provider
'''
@staticmethod
def usageToDict(item, perm):
'''
Convert a calRule db item to a dict for a rest response
:param item: Service item (db)
:param full: If full is requested, add "extra" fields to complete information
'''
retVal = {
'id': item.uuid,
'name': item.name,
'comments': item.comments,
'start': item.start,
'end': item.end,
'frequency': item.frequency,
'interval': item.interval,
'duration': item.duration,
'duration_unit': item.duration_unit,
'permission': perm
}
return retVal
def getItems(self, parent, item):
# Check what kind of access do we have to parent provider
perm = permissions.getEffectivePermission(self._user, parent)
try:
if item is None:
return [CalendarRules.usageToDict(k, perm) for k in parent.rules.all()]
else:
k = parent.rules.get(uuid=processUuid(item))
return CalendarRules.usageToDict(k, perm)
except Exception:
logger.exception('itemId {}'.format(item))
self.invalidItemException()
def getFields(self, parent):
return [
{'name': {'title': _('Rule name')}},
{'start': {'title': _('Starts'), 'type': 'datetime'}},
{'end': {'title': _('Ends'), 'type': 'date'}},
{'frequency': {'title': _('Repeats'), 'type': 'dict', 'dict': dict((v[0], six.text_type(v[1])) for v in freqs) }},
{'interval': {'title': _('Every'), 'type': 'callback'}},
{'duration': {'title': _('Duration'), 'type': 'callback'}},
{'comments': {'title': _('Comments')}},
]
def saveItem(self, parent, item):
# Extract item db fields
# We need this fields for all
logger.debug('Saving rule {0} / {1}'.format(parent, item))
fields = self.readFieldsFromParams(['name', 'comments', 'frequency', 'start', 'end', 'interval', 'duration', 'duration_unit'])
if int(fields['interval']) < 1:
self.invalidItemException('Repeat must be greater than zero')
# Convert timestamps to datetimes
fields['start'] = datetime.datetime.fromtimestamp(fields['start'])
if fields['end'] != None:
fields['end'] = datetime.datetime.fromtimestamp(fields['end'])
calRule = None
try:
if item is None: # Create new
calRule = parent.rules.create(**fields)
else:
calRule = parent.rules.get(uuid=processUuid(item))
calRule.__dict__.update(fields)
calRule.save()
except CalendarRule.DoesNotExist:
self.invalidItemException()
except IntegrityError: # Duplicate key probably
raise RequestError(_('Element already exists (duplicate key error)'))
except Exception as e:
logger.exception('Saving calendar')
raise RequestError('incorrect invocation to PUT: {0}'.format(e))
return self.getItems(parent, calRule.uuid)
def deleteItem(self, parent, item):
logger.debug('Deleting rule {} from {}'.format(item, parent))
try:
calRule = parent.rules.get(uuid=processUuid(item))
calRule.calendar.modified = getSqlDatetime()
calRule.calendar.save()
calRule.delete()
except Exception:
logger.exception('Exception')
self.invalidItemException()
return 'deleted'
def getTitle(self, parent):
try:
return _('Rules of {0}').format(parent.name)
except Exception:
return _('Current rules')

View File

@ -0,0 +1,39 @@
{% load i18n %}
<div class="row">
<div class="col-xs-12">
<h1>{% trans 'Accounts' %}</h1>
</div>
</div><!-- /.row -->
{% if messages %}
<div class="row">
<div class="col-md-offset-2 col-md-8">
{% for message in messages %}
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
{{ message }}
</div>
{% endfor %}
</div>
</div>
{% endif %}
{% verbatim %}
<div class="row">
<div id="{{ accounts }}" class="col-xs-12"></div>
</div>
<div id="detail-placeholder" class="row hidden">
<div class="col-xs-12">
<ul class="bottom_tabs nav nav-tabs">
<li class="active"><a href="#{{ usage }}_tab" data-toggle="tab">{% endverbatim %}{% trans 'Rules' %}{% verbatim %}</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active" id="{{ usage }}_tab">
<div class="row">
<div class="col-xs-12" id="{{ usage }}">
</div>
</div>
</div>
</div>
</div>
</div>
{% endverbatim %}

4
udsProxy/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
bin
pkg
vars
src/gopkg.in

View File

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>udsProxy</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.python.pydev.PyDevBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.python.pydev.pythonNature</nature>
</natures>
</projectDescription>

View File

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?eclipse-pydev version="1.0"?><pydev_project>
<pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH">
<path>/${PROJECT_DIR_NAME}/src</path>
</pydev_pathproperty>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
</pydev_project>

View File

@ -0,0 +1,84 @@
package main
import (
"fmt"
"log"
"net"
"net/http"
"strconv"
"strings"
"time"
ini "gopkg.in/ini.v1"
)
const configFilename = "/etc/UDSProxy.cfg"
var config struct {
Broker string `ini:"broker"` // Broker address
}
// Test service
func testService(w http.ResponseWriter, r *http.Request) {
if strings.Split(r.RemoteAddr, ":")[0] != config.Broker {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "Access denied")
}
r.ParseForm()
ip, port, timeOutStr := r.FormValue("ip"), r.FormValue("port"), r.FormValue("timeout")
if ip == "" || port == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Invalid arguments")
return
}
if timeOutStr == "" {
timeOutStr = "4"
}
timeOut, _ := strconv.Atoi(timeOutStr)
fmt.Println("Args: ", ip, port)
con, err := net.DialTimeout("tcp", ip+":"+port, time.Duration(timeOut)*time.Second)
if err == nil {
con.Close()
w.WriteHeader(http.StatusFound)
fmt.Fprint(w, "ok")
} else {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, err)
}
}
func actor(w http.ResponseWriter, r *http.Request) {
// Get Request as received and forward it to UDS, withouch changing anything...
// We will net params, body, etc...
r.ParseForm() // parse arguments, you have to call this by yourself
fmt.Println(r.Form) // print form information in server side
fmt.Println("path", r.URL.Path)
fmt.Println("scheme", r.URL.Scheme)
fmt.Println(r.Form["url_long"])
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("val:", strings.Join(v, ""))
}
fmt.Fprintf(w, "Hello astaxie!") // send data to client side
}
func main() {
cfg, err := ini.Load(configFilename)
if err != nil {
log.Fatal(err)
}
cfg.MapTo(&config)
fmt.Println("Broker address: ", config.Broker)
http.HandleFunc("/actor", actor) // set router
http.HandleFunc("/testService", testService)
err = http.ListenAndServe(":9090", nil) // set listen port
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}

View File

@ -1,40 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import SimpleHTTPServer
import SocketServer
PORT = 9090
if __name__ == "__main__":
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "Serving at port ", PORT
httpd.serve_forever()