jueves, 2 de mayo de 2019

Docker: Eliminar Todas las Imagenes y Contenedores


Docker: Eliminar Todas las Imagenes y Contenedores


Hoy solo quiero compartir un breve apunte: cómo eliminar todas las imágenes y contenedores de docker que tenemos en el sistema.
A veces estamos experimentando con la creación de imágenes en docker y nos damos cuenta de que tenemos demasiadas ya creadas, o demasiados contenedores, los cuales pueden ocupar bastante espacio. Por ejemplo el otro día en el trabajo, por un editor mal configurado (no era emacs) cada vez que se iniciaba el editor creaba un nuevo contenedor con una copia del código y sus dependencias, por lo que a los pocos días te dejaba sin espacio en disco.
Bueno, pues con este par de líneas, que si queremos podemos meter dentro de un script, podremos eliminar todo de un golpe, OJO: BORRA TODO!!!

Eliminar todas las imágenes de docker

docker rmi $(docker images -q)

Eliminar todos los contenedores de docker

docker rm $(docker ps -a -q)
Un pequeño apunte: si una de los contenedores está en ejecución deberemos usar la opción -fpara forzar la eliminación, o bien detener la ejecución.

Parar Stop todos los contenedores

docker stop $(docker ps -a -q)
Parar todos los contonedores



Share:

martes, 30 de abril de 2019

Diseñador de Apis YAML OpenAPI

Diseñador de OPENAPI

Interfaz de diseño para crear archivos de especificación OpenAPI (Swagger). Demo en vivo

Setup

0.-Tenga una instalación de Node.js que no sea demasiado antigua 
(v4 + debería funcionar para todo).

1.-Instale Aurelia CLI (npm install -g aurelia-cli)

2.-Clone este repositorio (git clone https://github.com/apinf/open-api-designer.git)

3.-Instale dependencias (npm install)

4.-Cree el código (au build) y abra index.html O ejecute el servidor web integrado en Aurelia usando au run y abra la URL que se imprime después de la construcción (generalmente http://localhost:9000)

Docker

  0.-Siga las instrucciones de configuración paso # 2
  1. Run docker build -t openapi-designer . (Run with --build-arg env=prod to compile the production version.)
  2. Run docker run -p <port>:80 openapi-designer replacing <port> with the port you want the app to be accessible at.
  3. The designer should now be accessible at http://localhost:<port>

Share:

domingo, 10 de marzo de 2019

Change the Default Mediation Flow of API Requests

Change the Default Mediation Flow of API Requests



Saltar al final de los metadatos
Ir al inicio de los metadatos
This tutorial uses the WSO2 API Manager Tooling Plug-in.
The API Gateway has a default mediation flow for the API invocation requests that it receives. You can extend this default mediation flow to do additional custom mediation for the messages in the API Gateway. An extension is provided as a synapse mediation sequence. You design all sequences using a tool such as the WSO2 API Manager Tooling Plug-in and then store the sequence in the Gateway's registry. 
Let's see how to create a custom sequence using the WSO2 API Manager Tooling Plug-in and then deploy and use it in your APIs.
  1. Log in to the API Publisher.
  2. Click Add to create an API with the following information and then click Next: Implement >.
    Field

    Sample value
    Name
    YahooWeather
    Context
    /weather
    Version
    1.0
    ResourcesURL patterncurrent/{country}/{zipcode}

    Request types
    GET method to return the current weather conditions of a zip code that belongs to a particular country
  3. The Implement tab opens. Select Managed API, provide the information given in the table below and click Manage.
    Field
    Sample value
    Endpoint typeHTTP/REST endpoint
    Production endpoint
    You can find the Yahoo weather API's endpoint from https://developer.yahoo.com/weather/. Copy the part before the '?' sign to get this URL: https://query.yahooapis.com/v1/public/yql
    To verify the URL, click the Test button next to it.
    Sandbox endpointhttps://query.yahooapis.com/v1/public/yql To verify the URL, click the Test button next to it.
  4. Click Next: Manage > to go to the Manage tab, provide the following information and click Save & Publish once you are done.
    Field
    Sample value
    Tier AvailabilityGold
    Keep the default values for the other attributes
  5. Download and install the WSO2 API Manager Tooling Plug-in if you have not done so already. Open Eclipse by double clicking the Eclipse.appfile inside the downloaded folder. 
  6. Click Window > Open Perspective > Other to open the Eclipse perspective selection window. Alternatively, click the Open Perspective icon shown below at the top right corner.
  7. On the dialog box that appears, click WSO2 APIManager and click OK.
  8. On the APIM perspective, click the Login icon as shown below.
     
  9. On the dialog box that appears, enter the URL, usernameand password of the Publisher server.
  10. On the tree view that appears, expand the folder structure of the existing API.
  11. Right-click on the in sequence folder and click Create to create a new in sequence.

    This is because you want the custom sequence to be invoked in the In direction or the request path. If you want it to be involved in the Out or Fault paths, select the respective folder under customsequences.
    Tip: If you prefer not to use the registry to upload the sequence or want to engage a sequence to all APIs in the APIM at once, you can do so by saving the mediation sequence XML file in the file system. See Adding Mediation Extensions for details.
  12. Name the sequence YahooWeatherSequence.
  13. Your sequence now appears on the Developer Studio console. From under the Mediators section, drag and drop a Property mediator to your sequence and give the following values to the property mediator. 
    The Property Mediator has no direct impact on the message, but rather on the message context flowing through Synapse. You can retrieve the properties set on a message later through the Synapse XPath Variables or the get-property() extension function. In this sequence, we are using two property mediators and set a Synapse XPath variable and a get-property() function to the two mediators respectively to retrive the properties setto the message context during the execution.
    Property NameNew Property
    New Property NameYQL
    Value TypeExpression
    Value Expression
    For the XPath expression, we take a part of the query in the Yahoo API's endpoint (https://developer.yahoo.com/weather/) and concatenate the zip code and country to it using the synapse get-property XPath expression:
    concat('?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22',syn:get-property('uri.var.zipcode'),',',syn:get-property('uri.var.country'),'%22)&format=json')
    Property Scope
    Synapse
    Since this is a mediation level Property keep the Property Scope as Synapse. This is the default scope set when no Property Scope is defined.
  14. Similarly, add another property mediator with the following values. This is an HTTP transport property that appends its value to the address endpoint URL. Once you are done, save the sequence.
    Property NameNew Property
    New Property NameREST_URL_POSTFIX
    Value TypeExpression
    Value Expressionget-property('YQL')
    Property Scope
    Axis2
    Since this is a transport level property, set the Property Scope as Axis2.
  15. Save the sequence.
  16. Right-click on the sequence and click Commit File to push the changes to the Publisher server.
  17. Log back in tothe API Publisher, select the API that you created earlier and click the Edit link right next to its name to go to the edit wizard.
  18. Navigate to the API's Implement tab, select the Enable Message Mediation check box and select the sequence that you created for the In flow. Next, click Manage and Save & Publish the API again.
    Tip: It might take a few minutes for the sequence to be uploaded into the API Publisher. If it isn't there, please check again later.
    When selecting a mediator, make sure that it is a non-blocking mediator as blocking mediators are not supported in API Gateway custom mediations. For more details, see Adding Mediation Extensions.
  19. Open the API Store, subscribe to the API that you just published and generate the access tokens in order to invoke the API.
  20. Click the API Console tab of the API. It opens the integrated API Console using which you can invoke the API.
  21. Give the following values for the parameters and invoke the API. You can also give any other value of your choice.
    country
    usa
    zipcode95004
  22. Note the response that you get as a JSON object from Yahoo.
In this tutorial, you created a sequence to change the default mediation flow of API requests, deployed it in the API Gateway and invoked an API using the custom mediation flow.
Please note that following mediators are not usable within custom sequences since they are not supported by API Gateway custom medications.
  • Call mediator in non-blocking mode
  • Send mediator
Share:

Editar una API usando la interfaz de usuario de Swagger

Edit an API Using the Swagger UI


WSO2 API Manager has an integrated Swagger UI, which is part of the Swagger project. 
Swagger is a 100% open source, standard, language-agnostic specification and a complete framework for describing, producing, consuming, and visualizing RESTful APIs, without the need of a  proxy or third-party services. Swagger allows consumers to understand the capabilities of a remote service without accessing its source code and interact with the service with a minimal amount of implementation logic. Swagger helps describe a service in the same way that interfaces describe lower-level programming code. 
The Swagger UI is a dependency-free collection of HTML, JavaScript, and CSS that dynamically generate documentation from a Swagger-compliant API. Swagger-compliant APIs give you interactive documentation, client SDK generation and more discoverability. The Swagger UI has JSON code and its UI facilitates easier code indentation, keyword highlighting and shows syntax errors on the fly. You can add resource parameters, summaries and descriptions to your APIs using the Swagger UI.
Also, see the Swagger 2.0 specification.
In this tutorial, let's see how you can add interactive documentation to an API by directly editing the Swagger code and through the API Publisher UI.
This tutorial uses the PhoneVerification API created in Create and Publish an API.
  1. Log in to the API Publisher and choose to design a new API.
  2. In the Design tab, give an API name, a context and a version, and click the Edit Source button under the API Definition section.
  3. The Swagger UI opens. Add the following code under the paths object. It adds a resource with two HTTP methods into the API.
    Tip:
    In the below code, note that you have a resource defined with the URL pattern /CheckPhoneNumber under the paths object. This is followed by the HTTP methods GET and POST. For each HTTP method, the following parameters are defined.
    • responses: An object to hold responses that can be used across operations. See the Swagger specification for details.
    • x-auth-type: WSO2-specific object to define the authentication type of the method.
    • x-throttling-tier: WSO2-specific object to define the throttling tier of the method.

    /CheckPhoneNumber:
        get:
          responses:
            '200':
              description: ''
          x-auth-type: Application & Application User
          x-throttling-tier: Unlimited
        post:
          responses:
            '200':
              description: ''
          x-auth-type: Application & Application User
          x-throttling-tier: Unlimited

  4. Click Apply Changes. Back in the API Publisher, note that a resource with two HTTP methods are added to the API.

    Let's say the backend of this API sends the response in XML format. Let's document this under the GET method in the resource that we just added. 
  5. Click Edit Source and add the following code under the GET method.
    produces:
            - text/xml
  6. Click Apply Changes. Back in the API Publisher, expand the GET method and note that the response content type has changed to XML. 
    Tip: You can use this attribute to document the type of the response message that the backend sends. It doesn't do any message type conversion. You can add multiple values as a comma-separated list. E.g.,
    produces:
    - text/xml, application/json
  7. Click Edit Source and add the following code under the GET method. It adds two parameters to the method.
    parameters:
            - name: PhoneNumber
              in: query
              required: true
              type: string
              description: Give the phone number to be validated
            - name: LicenseKey
              in: query
              required: true
              type: string
              description: Give the license key as 0 for testing purpose
  8. Click Apply Changes. Back in the API Publisher, note the two parameters with their descriptions that are added under the GET method.
  9. Click Edit Source again and add the following summary and description to the GET method.
    summary: Check the validity of your phone number
    description: "Phone Verification validates a telephone number and returns carrier information, location routing etc."
  10. Click Apply Changes. Back in the API Publisher, note the summary and description appearing under the GET method.
  11. In the Swagger UI, add the following code under the POST method. It adds two parameters as PhoneNumber and LicenseKey to pass the payload in. It also changes the datatypes of the parameters to application/x-www-form-urlencoded as the backend expects that datatype.
    consumes:
            - application/x-www-form-urlencoded
          parameters:
            - name: PhoneNumber
              in: formData
              required: true
              type: string
              description: Give the phone number to be validated
            - name: LicenseKey
              in: formData
              required: true
              type: string
              description: Give the license key as 0 for testing purpose
  12. Click Apply Changes. Back in the API Publisher, note the parameters that you added are visible under the POST method.
  13. In the Swagger API, change the title of the API as follows. This is the title that is visible to the consumers in the API Store, after the API is published.
    info:
      title: PhoneVerificationAPI

    You will see how this change is reflected in the API Store in step 15. 
  14. Click Apply Changes and complete the rest of the API creation process. Once you are done, click Save and Publish on the Manage tab to publish the API to the API Store.
  15. Log in to the API Store and click on the API that you just published.
  16. The API opens. Go to its API Console tab and note the changes that you did earlier now appearing in the API Store for consumers.
In this tutorial, you have seen how the integrated Swagger UI can be used to design, describe and document your API, so that the API consumers get a better understanding of what the API's functionality is.
Share: