aboutsummaryrefslogtreecommitdiffstats
path: root/zmqauth/zmq_auth_gen/create_certificate.py
blob: 2c4445dbb1a907200c67d218930f62633e2bd38d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
#  Copyright 2016 Rémi Duraffort <remi.duraffort@linaro.org>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#

import argparse
import zmq.auth


def main():
    """
    Parse options and create the certificate
    """
    parser = argparse.ArgumentParser(description="")
    parser.add_argument("--directory", type=str,
                        default="/etc/lava-dispatcher/certificates.d",
                        help="Directory where to store the certificates")
    parser.add_argument(type=str, dest="name",
                        help="Name of the certificate")
    args = parser.parse_args()

    # Create the certificate
    print("Creating the certificate in %s" % args.directory)
    zmq.auth.create_certificates(args.directory, args.name)
    print(" - %s.key" % args.name)
    print(" - %s.key_secret" % args.name)


if __name__ == '__main__':
    main()
ing.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
/*
 * Copyright (C) 2017-2018 "IoT.bzh"
 * Author Clément Bénier <clement.benier@iot.bzh>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package xdsservertest

import (
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"sync"
	"testing"
	"time"

	common "gerrit.automotivelinux.org/gerrit/src/xds/xds-common.git/golib"
	"gerrit.automotivelinux.org/gerrit/src/xds/xds-server/lib/xsapiv1"
	socketio_client "github.com/sebd71/go-socket.io-client"
)

// IOSockClient
type IOSockClient struct {
	URL       string
	Conn      *socketio_client.Client
	Options   *socketio_client.Options
	EmitMutex *sync.Mutex
	Connected bool
	//ServerDiscoChan chan Disconnection
	EscapeKeys []byte
}

//global client
var HTTPCli *common.HTTPClient
var logDir string
var sCli *IOSockClient

func Debug(t *testing.T, args ...interface{}) {
	if os.Getenv("VERBOSE") != "" {
		t.Log(args)
	}
}

func Debugf(t *testing.T, format string, args ...interface{}) {
	if os.Getenv("VERBOSE") != "" {
		t.Logf(format, args)
	}
}

func Copy(src, dst string) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()

	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, in)
	if err != nil {
		return err
	}
	return out.Close()
}

func initEnv(launchProcess bool) {
	if launchProcess {
		/*kill xds-server if needed*/
		cmd := exec.Command("killall", "-9", "xds-server")
		if err := cmd.Start(); err != nil {
			log.Fatal(err)
		}
		cmd.Wait()
	}
	/*set environment variable*/
	rootTestLog := "/tmp/xds-server-test"
	if err := os.Setenv(envRootCfgDir, rootTestLog); err != nil {
		log.Fatal(err)
	}
	sdkDir := rootTestLog + "/sdks/"
	if err := os.Setenv(envXdtSdk, sdkDir); err != nil {
		log.Fatal(err)
	}
	if err := os.Setenv(envXdsServerWorkspaceDir, rootTestLog); err != nil {
		log.Fatal(err)
	}
	if err := os.Setenv(envXdsServerRootCfgDir, rootTestLog); err != nil {
		log.Fatal(err)
	}
	if err := os.Setenv("XDS_LOG_SILLY", "1"); err != nil {
		log.Fatal(err)
	}
	/*remove and recreate working directories*/
	os.RemoveAll(rootTestLog)
	os.MkdirAll(rootTestLog, 0755)
	logDir = rootTestLog + "/logs/"
	os.MkdirAll(logDir, 0755)
}

/*prepare xds-server process*/
func launchXdsServer(proc **os.Process) *os.File {
	logFile := logDir + logFileXdsServer
	file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatal(err)
	}
	tmpProc, err := os.StartProcess(argsProcess[0], argsProcess, &os.ProcAttr{
		Files: []*os.File{os.Stdin, file, file},
	})
	if err != nil {
		log.Fatal(err)
	}
	*proc = tmpProc
	return file
}

func getHTTPClient(lvl int) (*common.HTTPClient, *os.File) {
	logFile := logDir + logFileClient
	file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatal(err)
	}
	conf := common.HTTPClientConfig{
		URLPrefix:           "/api/v1",
		HeaderClientKeyName: "Xds-Sid",
		CsrfDisable:         true,
		LogOut:              file,
		LogPrefix:           "XDSSERVERTEST: ",
		LogLevel:            lvl,
	}
	cli, err := common.HTTPNewClient(prefixURL, conf)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("HTTP session ID : %v", cli.GetClientID())
	var ver xsapiv1.Version
	err = cli.Get("/version", &ver)
	if err != nil {
		log.Fatal(err)
	}
	return cli, file
}

func NewIoSocketClient(url, clientID string) (*IOSockClient, error) {
	var err error

	sCli := &IOSockClient{
		URL:       url,
		EmitMutex: &sync.Mutex{},
		Options: &socketio_client.Options{
			Transport: "websocket",
			Header:    make(map[string][]string),
		},
	}
	sCli.Options.Header["XDS-SID"] = []string{clientID}

	sCli.Conn, err = socketio_client.NewClient(url, sCli.Options)
	if err != nil {
		return nil, fmt.Errorf("IO.socket connection error: " + err.Error())
	}

	sCli.Conn.On("connection", func() {
		sCli.Connected = true
	})

	sCli.Conn.On("disconnection", func(err error) {
		log.Printf("WS disconnection event with err: %v\n", err)
		sCli.Connected = false
	})

	log.Printf("Connect websocket with url=%v clientId=%v\n", prefixURL, HTTPCli.GetClientID())
	return sCli, nil
}
func TestMain(m *testing.M) {
	/* useful for debugging, preventing from launching xds-server
	 * it can be launch separetly */
	launchProcess := true
	log.Printf("TestMain: launchProcess is %v, so launching xds-server", launchProcess)
	initEnv(launchProcess)

	var proc *os.Process
	var fileXdsServer *os.File
	if launchProcess {
		fileXdsServer = launchXdsServer(&proc)
		go func(p *os.Process) {
			log.Print("xds-server is launching")
			if status, err := p.Wait(); err != nil {
				log.Fatalf("status=%v\n err=%v\n", status, err)
			}
		}(proc)
		defer proc.Kill()
		defer fileXdsServer.Close()
	}
	time.Sleep(1 * time.Second)

	lvl := common.HTTPLogLevelDebug
	var fileHTTPClient *os.File
	HTTPCli, fileHTTPClient = getHTTPClient(lvl)
	defer fileHTTPClient.Close()
	var err error
	sCli, err = NewIoSocketClient(prefixURL, HTTPCli.GetClientID())
	if err != nil {
		log.Fatal(err)
	}

	if HTTPCli == nil {
		log.Fatal("HTTPCLi is nil")
	}
	res := m.Run()
	defer os.Exit(res)
}