Кот канарский полосатый толстый

VALID INFO! My crazy life!

Задержись в реальности!

Разработка REST API приложения на GOLANG (сборник материалов)
Серьёзно о главном
r3code
SQL Работа с БД https://github.com/jmoiron/sqlx
 

Новая библиотека для работы с JSON-RPC 2.0 в Free Pascal, Delphi
Codded
r3code
После эксплуатации первой версии библиотеки https://github.com/r3code/pascal-jsonrpc-lite я решил ее переработать и сделать более удобной для работы. В итоге родилась вторая версия pascal-jsonrpc-lite-2 в которой улучшено определение типов сообщений и добавлена проверка структуры  и типов данных согласно спецификации. Описание и тесты также обновлены.
Доступно для загрузки с https://github.com/r3code/pascal-jsonrpc-lite-2

Прочитано: API Strategy and Architecture: A Coordinated Approach
Серьёзно о главном
r3code
Исходник https://www.ca.com/content/dam/ca/us/files/ebook/api-strategy-and-architecture-a-coordinated-approach.pdf

Что узнал?

Предлагают использовавть инструменты проектирования без написания кода изначально:

  1. apiary.io - инструмент, позволяет написать прототип без кода.

  2. RAML.org и SWAGGER.io - языки описания API, помогают пользователям использовать прототип API.

Товарищи делят архитектуры API на стили:

  1. Web Service (тунелирование) - транспортонезависим, много утилит, WSDL/SOAP/RPC, не годно для мобильных устройств, трудная разработка.

  2. Прагамтичный REST (URI) - веб-ориентирован для разработки интерфейсов интеграции, использует URI вместо WSDL, полагается на HTTP транспорт, часто назвают как "Web API", "" RESTful API", не полностью выполняют требования подхода REST, популярен из-за URI, пригоден для разработки веб и мобильных приложений, сейчас встречается в большинстве проектов, не является идеальным решением из-за доменоориентированности, ограничен 4 методами, структура URI не стандартна, не подходит для обмена большим числом мелких сообщений (IoT).

  3. Гипермедиа (настоящий REST) - основан на HTTP, URI; полностью выполняет принципы подхода REST хорошо масштабируется, хорошо споектированный API может позволить поддерживать новый приложения годами; мало инструментов для разработки; более медленная разработка по сравнению с 3, малоизвестна разработчикам.

  4. Событийный (Event-Driven, aka IoT) - транспортонезвисим, малая изибыточность, лучшая производительность при наличии большого количества мелких сообщений между бекэндом и фронтендом, хорош для игр, чатов и IoT, модель запрос-ответ делает разработку приложений сложенее для разработчиков.


Сохранено: RESTful SNMP Over HTTP. Part 4 / Marco Bresciani · Mar. 17, 17
Серьёзно о главном
r3code
Часть 1, часть 2, часть 3, часть 4.

Part IV

Commercial value allows you to uniquely map the entirety of SNMP operations and MIB data structures to HTTP protocol and URIs.

Let's see how we can possibly use everything we've read until now, with some additional RESTful views of similar behaviors, possible implementations, and further ideas.

Commercial Value

Let's take a look at the value, benefits, and more of commercial value.

Value and Benefits

The invention allows us to uniquely map the whole SNMP operations and MIB data structure to HTTP protocol and URIs, providing a more modern way to present such data structure and introducing the concept of uniform interface, allowing the data system (or the network device) to produce a uniform content regardless the type of the user by focusing only on the actual request format and content.

This solution allows implementing one single unique system that does not need to have custom implementations and interactions based on the user or software type that it is interacting with. The solution proposed, instead, is a uniform and unique interface that focuses its attention on the received URIs only, together with HTTP protocol header details, in order to comply with such requests and to produce one answer that fits all needs (or, more specifically, an answer that fits the specific request by the user).

Instead of producing one SNMP interface, one set of web services with related WSDLs, and one complex web-based (or desktop-based) GUI, the solution allows the product to be released with only the SNMP specification. The rules can translate the MIB into URIs (depicted by this solution) and a general-purpose, even third-party, simple software that is RESTful aware and can send general purpose HTTP request as per user customizations (i.e., one REST client plugin for Mozilla Firefox is about 100kB, while a MIB browser software application is at least one magnitude order bigger).

Likelihood of Use

Regardless the technology through which this solution is implemented, providing this kind of unique interface for all interactions (either human- or software-based) allows network devices internal software to be smaller and simpler, needing to fulfill single specific requests without any need to know the details of the interacting party. It’s then reasonable that other may introduce this idea and solution in other products in order to simplify their implementation, the embedded web-based software and the interactions between the user, and the internal set of data — thus reducing the number of bugs, the need for custom and specific user interfaces with a complex user experience, and so on.

How to Identify

Since the mapping rule is clear and well-defined, it should be very easy to identify an OID from an HTTP(S) request (or response) URI, giving us very easy visibility for the invention. Since the usage mechanisms depend on the mapping and all the other options described, the mapping itself and its rules should also be described in the product documentation for user needs.

How to Design Around

This solution is very broad. It is easy to design extensions, enhancements, and different usages around it since REST and RESTful ROAs are wide and general-purpose concepts that easily scale and extend.

It is easy to understand how, for example, this idea could become a method to manage file systems through an HTTP RESTful interface. Files in a network device, but not necessarily only those, may use this solution and idea. Using the URIs to map file system tree and its directories and files, this idea can work as a RESTful HTTP-based FTP protocol.

Replacing FTP-specific commands with uniform URIs (such as URI_ROOT/usr/lib/cups/gutenprint.5.2) means that the uniform interface may easily interact with those file via HTTP methods.

Specifically, the GET method will retrieve files content when operating on a file, whereas it will retrieve directories listing when operating on a directory (URI_ROOT/usr/lib/cups/ in the example URI above). To retrieve information on files or directories even before GETting them, the HEAD method, as per its definition, is the proper solution.

The PUT method will instead be used to create a file (or a directory), as before, listing the filename in the URI exactly as above but using the PUT method and filling the HTTP entity-body with the file content, or, for example, leaving it empty to create a directory.

Again, to both delete a directory or a file with no differences, it is possible to use the DELETE method of HTTP protocol. At the same time, HTTPS for security and access permissions management allows authentication and authorization procedures.

So, with respect to FTP, there is no need for changing directory to ask for binary or ASCII format or other peculiarities. But the uniform RESTful HTTP interface easily maps a whole file system to URIs also providing operations for working on those files (retrieve from, add, and delete to the file system).

It is easy to write ftp://user@example.org/my/own/file.txt to retrieve a file through FTP from any Internet browser (but it is generally not possible to use sftp:// from the same browser since the protocol is unsupported).

It is also possible reading a directory listing or adding or deleting a file, but these operations generally need specific clients or permissions and there is no one common way to do all operations. Having the HTTP protocol DELETE and PUT methods allows simple usage of any kind of networking API for HTTP or RESTful client to send data to a specific URI. These data will become a file in the file system.

To further merge this idea with the RESTful SNMP mapping described above by simply attaching a mib/ string to the idea above, everything works perfectly with the MIB itself as a whole becoming a resource (/mib) with its transactions (/mib/t or simply /t). Everything else can do the same, so the URI that maps the /files resource may represent resources that are directories and files inside the network device and its file system. This kind of mapping extension may replace FTP (File Transfer Protocol).

Another extension, following the same concept, is the possibility to use the uniform interface and REST guidelines to map network device’s operating system commands generally used through Telnet or SSH. It requires care to carefully design each resource or command with its parameters, keeping the basic concept of the uniform interface usage without breaking the basic rules. Again, it is also possible merging internal commands with the ideas with the URI/commands or /c and so on.

Speaking of actual implementations, it is reasonable (and probably mandatory!) to define and implement an automatic translation process converting actual MIB files to a set of proper configuration files for the software architecture so that URI mapping and resources interactions will be automatically mapped onto the application server depending on the MIB definition, leaving out all manual heavily error-prone conversion steps.

A plausible implementation that would help the ROA architect fulfil MIB specification, resources and users profiles: defining a general purpose framework able to receive the whole MIB (ASN.1) specification files as input, together with the set of user profiles and another set of configuration file (either YAML, XML, …) that maps user profiles permissions on each single resource.

Such a framework would take care of these inputs and should be able to provide a predefined scaffolding environment (a web application) that can reply to HTTP(S) requests according to MIB resources and user profiles and permissions. Since the inputs are static and standard and the behaviors are actually clear and predefined, this implementation should not be theoretically complex, assuming that the developers will define specific file formats for user profiles and resources/user permissions mapping.

There are frameworks already able to create data models, DB updates, GUI web pages and simple controllers starting from few data type definitions (see here for simple examples), so creating such automated environment should be the first step to defining a general implementation for the solution described here.

Smarter and better approaches for requests and responses formats may easily involve ontologies and semantic web, defining the MIB structure, data types, and objects relations through, for example, RDF (Resource Description Framework) or HTML5+RDFa that can be easily transformed via XSL(T) applications for better human or automatic parsing and management. A theoretical, brief, example structure of a URI_ROOT/1/3/6/1/2/1/1/1.en.html request may result in something like:


<html prefix="rdf http://www.w3.org/1999/02/22-rdf-syntax-ns#" lang="en">


  <head>


    <title>sysDescr</title>


    <meta http-equiv="Content-Type"


          content="application/xhtml+xml; -8" />


    <meta name="content-language" content="en" />


  </head>


  <body>


    <Description about="URI_ROOT/1/3/6/1/2/1/1/1.xml">


        <label xml:lang="en">sysDescr</ label>


        ...


    </Description>


  </body>


</html>

Thank you for reading this series. I had the idea for this article a few years back and quickly scratched it onto a piece of paper. Now, I've finally had the time to polish and publish it! I hope you've liked it and will use it — let me know!


Сохранено: RESTful SNMP Over HTTP. Part 3 / Marco Bresciani · Mar. 17, 17
Серьёзно о главном
r3code
Часть 1, часть 2, часть 3, часть 4.

Part III

Following these mapping rules and definitions, you can easily map almost all behaviors and operations defined by SNMP protocol.

Let's see how traps can be managed following SNMP needs and HATEOS guidelines.

Traps Management

Traps, together with InformRequest, are probably the most difficult SNMP operations to port in HTTP RESTful concepts. This is because the general HTTP behavior does not foresee connections coming from the server to the client, so the client may not be able to receive HTTP requests from the server. For this reason, the mapping of these operations is critical, and their implementation may heavily depend on needs and available resources.

The first solution (which is also the easiest) requires the simple creation of a trap resource at the uniform interface level, so create a specific URI like URI/ROOT/trap/ that identifies the ongoing notifications. The user is then able to GET such resource and to retrieve the list of modifications that are currently available, just as a GET on a tree element of the MIB outputs the list of contained objects.

At this level, it is possible to map the mere SNMP trap operation if the entity-body of the response contains the same information provided by actual SNMP traps (sysUpTime, OID, and optional variable bindings). Since then the main content of a trap is an OID, this idea describes the actual HTTP/URI mapping.

Another possibility, which less connected with the uniform interface of the ROA but is more related to the actual SNMP standard, is allowed by the HTTP 1.1 standard. Version 1.1 of HTTP allows clients to open a connection and keep it open. Through this connection, the server may send a response to the newly created trap immediately every time a trap is generated in the system.

In this situation, the single GET request to the URI/ROOT/trap/ resource remains continuously active while the operations in the network device are ongoing. The network device itself will send a part of a GET response containing data for a newly generated trap without closing the connection.

InformRequest Management

By extending the trap management described above, it is possible to implement the SNMP InformRequest the same way as the trap keeping the same /trap resource URI. Since the user must acknowledge to the system the fact that it has received the InformRequest, once the user retrieves the list of available notifications, it may use the HTTP TRACE method on the URI of a specific entry.

As specified by the standard, the TRACE method “invoke[s] a remote, application-layer loop- back of the request message.” To work in a safe and idempotent way with the trap and InformRequest resources, to inform the server that user has received such trap/InformRequest resource, and to receive a further confirmation from the server, the TRACE method is the only solution.

Let's analyze the usability of the other HTTP methods in the uniform interface perimeter. Except for the POST, they all are safe and idempotent so they would operate in the same way. Using DELETE will render the subject trap URI (plus OID) so that it's no longer available for further users that are acting on the same network device.

The results of GET get done on the /trap/{OID} URI and shall reflect the actual /{OID} resource identified by the trap and so the response changes accordingly. Instead of “200 OK,” the response should use a “303 See Other” response code, providing the actual OID (without the /trap element) of the identified resource.

By PUTting a trap resource (PUT method with the /trap prefix and the OID) to notify the server about user’s side reception, the uniform interface requires that a value is set for such resource or the resource itself would be modified. Since PUT modifies the resource, two or more users working on the same network device may hide possibly previous modifications with their own.

The other possible solution to the TRACE method would be the non-safe and non-idempotent use of the POSTT method from HTTP protocol.

Format and Language Customizations

HTTP protocol provides two specific header fields that have to use to request for a specific output format (Accept) and a specific language (Accept-Language). They shall both be used, whether needed and meaningful, to boost the usage of the uniform interface and the HTTP itself, but a couple of customizations (both user- and software-oriented) can be added to the description above, in order to simplify software clients implementation and human user interactions when these two qualities have to be constrained. These customizations are anyway fully compatible with the uniform interface and the ROA concepts depicted above.

The first customization is the human language of the results: adding, for example, .en, .ja, .it to a URI means that agent has requested to receive the content with English, Japanese or Italian translation. So the following URI, with postponed .en: URI_ROOT/1/3/6/1/mgmt/mib/system/sysDescr.en will provide resource content in English language, whether meaningful.

The second customization is the output format of the results: adding a desired output format to a URI, gives the user the possibility to ask for a specific output solution, still using the uniform interface of RESTful and resources management. The URI scheme URI_ROOT/1/3/6/1/2/1/1/1.json will reply with a JSON-formatted content whereas the URI with XML extension (as URI_ROOT/1/3/6/1/2/1/1/1.xml) will provide XML content to the requester, and so forth.

Obviously, the HTTP header fields are to be preferred, but these two solutions may simplify software implementation and may also help human user understanding the whole request and the expected output.

It is also possible to chain these two customizations (in any order) so that URI_ROOT/1/3/6/1/2/1/1/1.en.atom will provide the content in Atom format, English language.

Transaction-Like Behavior

RESTful SNMP can use this uniform interface and HTTP functionalities to introduce transactional-like behaviors for grouping operations (multiple SNMP SETs). This resembles the SNMP possibility to use one single request with multiple and possibly unrelated PDUs in the same request — usually to SET related values in one shot, even though the associated resources are different.

To push further on the uniform interface concept, transactions themselves are to be considered resources — but, instead of associating them to OIDs, they can be system-wide published and they can be queried onto through a URI like URI_ROOT/t/. Using this URI with the HTTP POST method, the user will be able to create new transactions letting the system provide the URI on to which act directly.

Mimicking a notable example from Sam Ruby and Leonard Richardson's RESTful Web Services, a possible sequence of operations to create a transaction would be POST /t HTTP/1.1 with a response 201 Created¶Location: /t/hg42. With this sequence of request/response, the system provides the user (human or automatic, whatever) the URI associated to the newly requested and created transaction.

This will be followed by the normal usage described above, except for the fact that the URI described above will be based on the URI /t/hg42 (as per the example) instead of /.

So, continuing the example, a PUT request to the OID 1.3.6.1.2.1.118.1.2.2 (alarmActiveTable) is done with URI_ROOT/t/hg42/1/3/6/1/2/1/118/1/2/2/535135/1/1373382000000/4;5;9 and to this further sequences of GET or PUT operations, or any other sequence according to user and network device needs, may follow.

Then, as per all transactions, the user may want to commit or rollback it according to the results of the single operations. The use of an HTTP DELETE request managed the rollback of the transaction at URI provided by the system (DELETE /t/hg42 HTTP/1.1 ) and the transaction rolls back with a 200 OK response.

Instead, whether the user wants to commit such transaction, the request would be similar, simply changing the HTTP method PUT /t/hg42 HTTP/1.1 and possibly (but not necessarily) adding a simple text entity-body with, say, “commit” and the transaction will be committed.

Again, fulfilling the uniform interface, the response may contain a list of performed operations, with their URIs, so the user may have a complete set of results.

From this point on, a committed transaction will not reply to a DELETE operation or will simply reply with a "403 Forbidden" response status. Depending on the implementation the automatic deletion of the transactional resource or to, probably better, keep it for future reference. With the same uniform interface, each time a resource exists, it can also reply to a DELETE request providing the status (open/on-going or commit/rollback) and possibly the list of performed requests/operations and their results.

Conclusion

Following these mapping rules and the definitions for indexing and filtering and the uniform usage of HTTP methods, you can be able to map in an easy way almost all behaviors and operations defined by SNMP protocol. HTTPS usage provides security (as per SNMPv3) and, with proper enhancements, output formats customizations are available.


Сохранено: RESTful SNMP Over HTTP. Part 2 / Marco Bresciani · Mar. 17, 17
Серьёзно о главном
r3code
Часть 1, часть 2, часть 3, часть 4.

Part II

Learn about the GET and SET operations in terms of attempting SNMP with RESTful mapping, along with some HATEOAS tips and tricks.

Today, we'll discuss mapping the GET and SET operations with some hints on HATEOAS guidelines.

Security

A first security option can be represented by the HTTP basic authentication “realm.” That is the string assigned by the server to identify the protection space of the Request-URI. It may be used to resemble the context/contextEngineID depicted in SNMP protocol and represented in the RFC 4088 URI scheme.

Thanks to HTTP capabilities and configuration parameters, according to the same functionalities provided by SNMP, it is up to the ROA architect together with the MIB specification to define and implement resource specificities and security constraints and behaviors. When doing an HTTP GET operation on a resource, for example, the user may simply receive the data back, whereas another resource may ask for username and password or it may refuse the access and so on according to MIB definition and needs. The responding device may render each resource (MIB object) and fields as read-only or not available for reading (for any reason) and so on.

With respect to actual networking security, is reasonable that HTTPS intrinsic security replaces SNMPv3 capabilities and it is theoretically even possible to apply this protocol usage in a more aimed and fine-grained way — specific resources as a whole or filtered resources parts may require the use of HTTPS while other resources may need HTTP basic authentication only, and so on.

Giving the HTTP basic authentication and enhanced security provided by HTTPS, the actual mapping between SNMPv2/v3 security capabilities and HTTP(S) is a surplus and no longer considered. Except for OID mapping and operations on resources, the idea described here considers the use of HTTP(S) authentication as mandatory to reflect the proper and correct use of the protocol (also considering that HTTP(S) security level is not inferior to SNMPv2/v3 one).

As said, then, it is up to MIB definition and ROA architect to provide the correct behavior of the resources according to security and users’ profiles and permissions.

Tree Parent Objects Mapping

When the user does a request on resources that do not represent actual value objects (either scalar or tabular), mapped to MIB elements without actual content (sub-trees, instead of leaves), then the HTTP responses and the REST concepts still fulfill the uniform interface — but the representation will describe the contained objects. For example, OID 1.3.6.1.2.1.118.1.2represents the .iso.org.dod.internet.mgmt.mib-2.alarmMIB.alarmObjects.alarmActive object and is not a leaf object itself (it contains alarmActiveTable at 1.3.6.1.2.1.118.1.2.2), so its representation shall necessarily describe the actual objects it contains.

Requesting the alarmActive resource at OID 1.3.6.1.2.1.118.1.2 will output a linked list of its children objects (and actual resources). For this example, the HTTP response body will contain links for these objects: alarmActiveTable, alarmActiveVariableTable, and all other tabular and scalar objects in this MIB area.

The actual output format contained in the HTTP response may easily depend on application or users’ needs.

This behavior still complies with REST and RESTful concepts, provides resources information, links resources between themselves, and describes a fully connected environment in which even resource containers are reachable and manageable as resources themselves. Simple output in this situation can leverage HTML5 or XHTML through <dl>/<dt>/<dd> sequences, <table> tags, and similar or specific XML, YAML, or JSON formats. The goal, again, is to keep a uniform interface for requests and responses, favoring MIB navigation and linking between resources whether the user does requests on MIB tree objects that are not leaves or on actual MIB data objects.

GetBulk and GetNext Requests Mapping

In order to complete the set of SNMP reading operations, there is the need to take care of GetNextRequest and GetBulkRequest. They are quite similar, in which GetBulkRequest is a sort of optimized version of the GetNextRequest operation. The GetNextRequest discovers available variables and values. The response contains the lexicographically next variable in the MIB. It is possible to walk the whole MIB with iterative requests starting at OID 0.

As per GetRequest, even GetNextRequest can specify columns filtering. The GetBulkRequest, instead, returns a set of multiple variable bindings (variables plus values) according to the request. The request can also specify max-repetitions and non-repeaters fields for further control. When asking for a simple OID not corresponding to an actual object but to a sub-tree (i.e., 1.3.6.1 for the whole iso.org.dod.internet MIB), the requestor receives links to sub-resources and sub-trees.

The user can automatically (or manually, for the human user) navigate them to explore the MIB or even automatically build its own data structure and content representation. It’s even possible to navigate the MIB through a sequence of RESTful GET operations and produce graphical views of the MIB (such as here or here) or directly ask for a graphical format of the same and so on.

A possible example of RESTful GET request to retrieve the MIB 1.3.6.1 above could be something like this:


GET /1.3.6.1 HTTP/1.1


Host: example.com:80


Accept: text/plain

Depending on the request, the acceptable types may differ: Accept: application/xml for W3C standard XML or Accept: text/html for classic HTML content and so on. The response to this request shall obviously contain the required content-type (whether available) and all the standard-required fields, together with the properly formatted content associated with required resource.


HTTP/1.1 200 OK


Content-Type: text/plain; -8


Date: Saturday, 26 April 2014 9:22:34 PM CEST


Server: RESTful SNMP 1.0


Allow: OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE


Connection: close


Directory: http://example.com:80/1.3.6.1.1


Management (mgmt): http://example.com:80/1.3.6.1.2


Experimental: http://example.com:80/1.3.6.1.3


Private: http://example.com:80/1.3.6.1.4


Security: http://example.com:80/1.3.6.1.5


SNMPv2: http://example.com:80/1.3.6.1.6


mail: http://example.com:80/1.3.6.1.7

These above, considering text/plain as request/response content-type, is a pure list of key-value pairs. Whether, for example, application/XML is needed, an example of (part of) the answer could be something like:


<element>


  <name>Management (mgmt)</name>


  <uri>http://example.com:80/1.3.6.1.2</uri>


</element>

Or, when it's classic text:


<a href=”http://example.com:80/1.3.6.1.6”>SNMPv2</a>

And so on, depending on requirements, specifications, and user needs. Limits to the actual format are the available MIME types.

For these reasons, the uniform interface could be considered a limitation with respect to Get{Bulk; Next}Request of SNMP protocol. Anyway, the uniform interface and usability of HTTP GET request as described above allows more flexibility and filtering options, leaving to application specificities and user needs the capability to browse literally through the MIB or to send multiple different (uniform) requests to many resources that can be later manipulated or computed in other ways to produce different results.

Since MIB represents a hierarchical data structure called a tree, both human and automatic users may adopt at least four possible tree traversal methods: pre-order, in-order, post-order, or level-order (breadth-first). Obviously, the ROA architect and designers can do more customizations to provide specific content in the link, location, or content-location headers in HTTP response or even provide specific clients that, according to GetBulkRequest or GetNExtRequest behaviors, may translate such behaviours in specific sequences of HTTP GET operations through the uniform REST interface.

The basics of this idea, however, still follow the REST and ROA concepts and require that the requesting an object (scalar, tabular, or sub-tree) shall provide all information to retrieve associated objects (mainly for sub-trees) in order to create a fully connected set of resources that can be browsed and navigated both automatically and manually.

SetRequest Mapping

Till now, simple reading operations (SNPM GET{Bulk; Next}Request corresponding to HTTP GET) have been considered. For writing operations, applying the uniform interface base concepts depicted above, the URI structures are, obviously, the same. For writing, an HTTP request body is required that contains the data for the MIB object.

Writing both scalar and tabular objects uses the HTTP PUT operation: scalar objects, when identified by URI, will respond to the HTTP PUT request modifying their value with the one provided in the HTTP request coming from the (human or software) agent.

For tabular objects, when identified by URI with possibly indexing and filtering components, the same writing capability is uniformly provided, stated that, obviously, the HTTP request body shall contain all needed data.

For scalar objects, the URI immediately identifies them, so the HTTP entity-body of the PUT operation contains the simple value. Using the HTTP entity-body will help the receiving system managing it, considering the Content-Type field describing the actual format of the data. It is simpler using the common “query string” mode (key=value): URI_ROOT/{resource}?objectName=newValue.

Since the key is already identified by the URI, URI_ROOT/slashed/OID/for/the/scalar/object?newValue could be used. The HTTP request will also contain the value description in the Content-Type field; this requires some care for URI encoding whether special characters are contained in the scalar object value.

For tabular objects, once the user knows the indexes, the PUT method is the only way to interact with a resource of the MIB: using the same GET scheme to create the URI, the HTTP entity-body shall contain the values for each and all the fields in the URI request.

If the URI aims a row with fixed columns (URI_ROOT/1/3/6/1/2/1/118/1/1/2/a_name/1342/1/4;6;9), the entity-body shall contain a set of key/value pair corresponding to the fields to be set. This can be done in any format, from JSON to XML to simple text-encoded key/value pairs like 7=42¶8=1701¶9=1974¶10=1975 and so on.

The usage of key/value pairs can be easily used for single rows modification putting them in the query string, with the usual common way beingURI_ROOT/1/3/6/1/2/1/118/1/1/2/?4=42&6=1701. When the user must write multiple rows, even if it is still possible to address each of them via specifically built entity-body contents, the suggestion is transforming the set of indexes in a set of distinct PUT operations, if possible, to better keep interface consistency.

Following above considerations, if the user must create a resource for which (any reason) it does not know its full URI, the SetRequest-equivalent operation must use the POST method. If some tables have specific server-side rules to build the indexes and these rules are not public, a possible POST request may be URI_ROOT/slashed/OID/for/the/tabular/object/list,of,columns that has the key-value pairs in the HTTP entity-body.

The system shall reply to the POST request with a “201 Created” status code response and the Location header field describing the full URI with the new system-built index that, as said, may rely on an internal DB indexing number, on a secret algorithm, or whatever. In this situation only, the POST may be used and the final URI would be: URI_ROOT/slashed/OID/for/the/tabular/object/system-built_index/list,of,column. And with this complete URI ,the user will be able to, from that moment on, autonomously GET from or PUT to that resource.


Сохранено: RESTful SNMP Over HTTP. Part 1 / Marco Bresciani · Mar. 17, 17
Серьёзно о главном
r3code
Попал на статью из Automatically convert SNMP service to REST API. А искал собственно информацию как SNMP можно переложить на REST принципы и сделать в виде веб-приложения доступ к настройкам. И действительно это возможно, ведь у HTTP и SNMP много общего, протокол без состояний, операции чтение и запись. Для управления устройством можно применить предложенную ниже модель, она позволяет использовать формальное описание объектов в MIB, а управлять через REST. Идея интересная, т.к. позволяет сохранить всю информацию для управления в четко определенном виде с всеми необходимыми данными о типах и прочем.

Далее текст статьи я сохраняю целиком, т.к. в первоисточнике он разбит на 4 части. Текст на английском.
Часть 1 ниже. Часть 2, часть 3, часть 4.
Read more...Collapse )

Автоматическая публикация стабильных сборок
Серьёзно о главном
r3code
Мне не очень нравиться менять на сайте ссылку на последнюю стабильную версию продукта вручную, я это совсем не люблю.
Чтобы это хоть как-то автоматизировать я придумал следующее.
Ссылка постоянна, имя файла содержит токлько главный номер версии.
Jenkins умеет публиковать артефакты сборки через FTP или в общую папку Windows. Я настроил послесборочные шаги так, чтобы архив с последним обновлением выкладывался по FTP в одну и ту же папку. Папка именуется так "корень-FTP/каталог-продукта/last/update/", для установочного дистрибутива папка "../last/dist". Задача очищает папку перед загрузкой новых артефактов, потому там будет самая новая версия. Каталог доступный по FTP одновременно доступен и веб-серверу, потому на сайте я просто указываю этот путь с http, например "http://example.org/files/pub/product-name/last/update/product-update.zip".

Автоматическая публикация стабильной сборки
Для автоматической публикации стабильной сборки серверу нужно знать, какая из них стабильная.
Тут два варианта:

  1. собирать последний созданный тег из хранилища;

  2. собирать из специальной ветки stable.

Мне больше нравиться вариант 2. Настроено это так: права на запистьв в ветку stable, есть только у разработчика отвечающего за выпуск версий, когда разработчики выпустили новую версию и зафиксировали ее в тег, ответственный за выпуск сливает этот тег в ветку stable.
Jenkins в задача publish-stable по расписанию проверяет в хранилище ветку stable и как обнаруживает обновление запускает сборку, конечный шаг которой публикация артефактов.
Так разработчику даже в Jenkins не надо заходить для публикации сборки, и в логе SVN остается след о публикации сбоки, видно когда была опубликована и кто одобрил ее.


Object Pascal: подборка интересных открытых библиотек кода
Серьёзно о главном
r3code
slf4p - фасад для нескольких библиотек для логгирования (LazLogger, Log4D и др.), проверено для FreePascal, Delphi 2009.
Daraja HTTP Framework - фреймворк для построения веб-приложений на Object Pascal (FreePascal, Delphi), веб-сервер на основе INDY.
Brook framework - фреймворк для построения веб-приложений на Object Pascal, последняя версия 3.0 2014 года, поддерживает REST/WEBSOCKET.



Защита от выполнения вредоносных PHP-скриптов на сайте
Серьёзно о главном
r3code
Для защиты:

  1. настроим доступ в htaccess;

  2. запретим опасные команды в PHP.ini;

  3. запишем нежалательные запросы для анализа;

  4. сбросим атакующему жирную свинью.

Read more...Collapse )

?

Log in

No account? Create an account